0

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
Community
  • 1
  • 1
sisdog
  • 2,649
  • 2
  • 29
  • 49

1 Answers1

1

The colname in 'meta' is factor class, so we need to convert this to character and use that to create new column in 'frm'

frm[as.character(meta[[1]])] <- 1
head(frm,2)
#  z y a b c
#1 1 1 1 1 1
#2 2 1 1 1 1

If we need to loop through the 'meta' names

for(cn in as.character(meta$colname)) frm[[cn]] <- 1
akrun
  • 874,273
  • 37
  • 540
  • 662