简体   繁体   中英

In R Add Columns From a Different Dataframe

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM