matekus matekus - 1 month ago 5
R Question

Convert single column dataframe to dataframe with multiple rows and named columns

dfOrig <- data.frame(rbind("1",
setnames(dfOrig, "Value")

I have a single column vector, which actually comprises two observations of three variables. How do I convert it to a data.frame with the following structure:

ID Code Tag
"1" "C" "531404"
"3" "B" "477644"

Obviously, this is just a toy example to illustrate a real-world problem with many more observations and variables.


Here's another approach - it does rely on the dfOrig column being ordered 1,2,3,1,2,3 etc.

x <- c("ID", "Code", "Tag")    # new column names
n <- length(x)                 # number of columns
res <- data.frame(lapply(split(as.character(dfOrig$Value), rep(x, nrow(dfOrig)/n)), 

The resulting data is:

> str(res)
#'data.frame':  2 obs. of  3 variables:
# $ Code: Factor w/ 2 levels "B","C": 2 1
# $ ID  : int  1 3
# $ Tag : int  531404 477644

As you can see, the column classes have been converted. In case you want the Code column to be character instead of factor you can specify stringsAsFactors = FALSE in the data.frame call.

And it looks like this:

> res
#  Code ID    Tag
#1    C  1 531404
#2    B  3 477644

Note: You have to get the column name order in x in line with the order of the entries in dfOrig$Value.

If you want to get the column order of res as specified in x, you can use the following:

res <- res[, match(x, names(res))]