如何使用R和dplyr同时为多个新列分配值?

问题描述 投票:1回答:2

特定

base <- data.frame( a = 1) 
f <- function() c(2,3,4)

我正在寻找一个解决方案,该解决方案将导致函数f应用于base数据帧的每一行,结果将附加到每一行。以下两项均无效:

result <- base %>% rowwise() %>% mutate( c(b,c,d) = f() )
result <- base %>% rowwise() %>% mutate( (b,c,d) = f() )
result <- base %>% rowwise() %>% mutate( b,c,d = f() )

这项任务的正确语法是什么?

这似乎是一个类似的问题(Assign multiple new variables on LHS in a single line in R),但我特别感兴趣用tidyverse的函数来解决这个问题。

r dplyr
2个回答
3
投票

我认为你要做的最好的是修改data.frame的do()。也许

base %>% do(cbind(., setNames(as.list(f()), c("b","c","d"))))

如果f()首先为不同的列返回一个列表,那可能是最好的。


0
投票

如果你愿意在没有dplyr的情况下这样做:

# starting data frame
base_frame <- data.frame(col_a = 1:10, col_b = 10:19)

# the function you want applied to a given column 
add_to <- function(x) { x + 100 } 

# run this function on your base data frame, specifying the column you want to apply the function to:
add_computed_col <- function(frame, funct, col_choice) {
  frame[paste(floor(runif(1, min=0, max=10000)))] = lapply(frame[col_choice], funct)
  return(frame)
}

用法:

df <- add_computed_col(base_frame, add_to, 'col_a')
head(df)

enter image description here

并根据需要添加任意数量的列:

df_b <- add_computed_col(df, add_to, 'col_b')
head(df_b)

enter image description here

重命名列。

© www.soinside.com 2019 - 2024. All rights reserved.