Reputation: 127
I have the following data:
data.frame("color" = c( c("red", "red"), c("red"), c("red","green") ), rownames=letters[1:3] )
And I would like to make it into a dataframe with the following structure:
color
a c("red", "red")
b c("red")
c c("red", "green")
where a
,b
and c
are rownames.
The code I have above doesn't produce this, so how do I go about creating such a dataframe?
EDIT: If I try to make the rownames as: paste("a",0:2,sep="",collapse=','), I get:
color
a0,a1,a2 c("red", "red")
a0,a1,a2 c("red")
a0,a1,a2 c("red", "green")
When what I want is:
color
a0 c("red", "red")
a1 c("red")
a2 c("red", "green")
How can I also rectify this?
Upvotes: 2
Views: 952
Reputation: 193527
You can use the I
function and put your vectors in a list
:
data.frame("color" = I(list(c("red", "red"),
c("red"),
c("red","green"))),
row.names=letters[1:3] )
# color
# a red, red
# b red
# c red, green
str(.Last.value)
# 'data.frame': 3 obs. of 1 variable:
# $ color:List of 3
# ..$ : chr "red" "red"
# ..$ : chr "red"
# ..$ : chr "red" "green"
# ..- attr(*, "class")= chr "AsIs"
Alternatively, with "data.table", you can create the list column directly (without I
) but data.table
s don't have row names, so you would need to add that as a column in your dataset.
library(data.table)
data.table("color" = list(c("red", "red"), "red", c("red", "green")),
"rownames" = letters[1:3])
# color rownames
# 1: red,red a
# 2: red b
# 3: red,green c
str(.Last.value)
# Classes ‘data.table’ and 'data.frame': 3 obs. of 2 variables:
# $ color :List of 3
# ..$ : chr "red" "red"
# ..$ : chr "red"
# ..$ : chr "red" "green"
# $ rownames: chr "a" "b" "c"
Upvotes: 3
Reputation: 13139
Use single quotes:
mydf <- data.frame(color = c( 'c("red", "red")', 'c("red")',
'c("red","green")' ), row.names=letters[1:3] )
> mydf
color
a c("red", "red")
b c("red")
c c("red","green")
Upvotes: 0