I'm an R noob! I'm trying to use one dataframe as metadata to create columns in another dataframe. I'm using apply but the columns aren't getting created. Ideas?
meta <- data.frame(colname = c("a","b","c"))
frm <- data.frame(z=c(1,2,3))
frm["y"] <- 1
colnames(frm)
apply(meta, 1, function(x) {
frm[x["colname"]] <- 1
})
colnames(frm) #hoping for a/b/c columns now
Which outputs:
> meta <- data.frame(colname = c("a","b","c"))
> frm <- data.frame(z=c(1,2,3))
> frm["y"] <- 1
> colnames(frm)
[1] "z" "y"
> apply(meta, 1, function(x) {
+ frm[x["colname"]] <- 1
+ })
[1] 1 1 1
> colnames(frm) #hoping for a/b/c columns now
[1] "z" "y"
UPDATE: found the answer here: how to access global/outer scope variable from R apply function?
Needed to access variables outside the scope of apply using <<-
meta <- data.frame(colname = c("a","b","c"))
frm <- data.frame(z=c(1,2,3))
frm["y"] <- 1
colnames(frm)
apply(meta, 1, function(x) {
frm[x["colname"]] <<- 1 #DBL ARROW DID IT
})
colnames(frm) #hoping for a/b/c columns now