r - How to add multiple columns to a data.frame simultaneously? -
i have following dataframe , vector:
ddf = data.frame(a=rep(1,10), b=rep(2,10)) xx = c("c", "d", "e", "f")
how can new empty columns named items in xx ?
i tried following not work:
ddf = cbind(ddf, data.frame(xx)) error in data.frame(..., check.names = false) : arguments imply differing number of rows: 10, 4
following not work:
for(i in 1:length(xx)){ ddf$(xx[i]) = "" } error: unexpected '(' in: "for(i in 1:length(xx)){ ddf$(" } error: unexpected '}' in "}"
this there:
ddf[xx] <- na # b c d e f #1 1 2 na na na na #2 1 2 na na na na #3 1 2 na na na na #...
you can't directly use ddf$xx
because try assign column called xx
rather interpreting xx
. need use [
, [<-
functions, using square brackets when dealing character string - ddf["columnname"]
.
the reason why selects columns because data.frames
lists essentially:
is.list(ddf) #[1] true as.list(ddf) #$a # [1] 1 1 1 1 1 1 1 1 1 1 # #$b # [1] 2 2 2 2 2 2 2 2 2 2
...with each column corresponding list entry. if don't use comma specify row, ddf["name",]
or column ddf[,"name"]
, column default.
Comments
Post a Comment