简体   繁体   中英

Adding multiple columns to a data frame

I have a data frame df such as:

df <- data.frame(a=1:5, b=101:105)

Now adding a single column to a specific row works:

df[4,"d"] <- 5
df
#   a   b  d
# 1 1 101 NA
# 2 2 102 NA
# 3 3 103 NA
# 4 4 104  5
# 5 5 105 NA

But adding multiple columns simultaneously doesn't!

df[3,c("b","f","g")] <- c(6,7,8)
#Error in `*tmp*`[[j]] : recursive indexing failed at level 2

What gives?

The long way to achieve this, of course, is:

df[3,"b"] <- 6
df[3,"f"] <- 7
df[3,"g"] <- 8

But is this really the easiest (and the right) way?

You can first assign new columns to the data, and then fill them by row (or by column).

df[ ,c("e","f","g")] <- NA
df
#   a   b  e  f  g
# 1 1 101 NA NA NA
# 2 2 102 NA NA NA
# 3 3 103 NA NA NA
# 4 4 104 NA NA NA
# 5 5 105 NA NA NA
df[3 ,c("e","f","g")] <- 6:8
df
#   a   b  e  f  g
# 1 1 101 NA NA NA
# 2 2 102 NA NA NA
# 3 3 103  6  7  8
# 4 4 104 NA NA NA
# 5 5 105 NA NA NA

A more automated way to achieve this is as follows:

df <- data.frame(a=1:5, b=101:105)
cols <- c("e", "f", "g")
vals <- c(6, 7, 8)
sapply(1:length(cols), function(i)
   df[3, cols[i]] <<- vals[i]
)
df

Which gives:

  a   b  e  f  g
1 1 101 NA NA NA
2 2 102 NA NA NA
3 3 103  6  7  8
4 4 104 NA NA NA
5 5 105 NA NA NA

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