在R函数中将列表转换为数据帧列
我有一个(非常简化的)函数形式如下在R函数中将列表转换为数据帧列,r,function,R,Function,我有一个(非常简化的)函数形式如下 doThing <- function(df){ result <- c() #Sets up dataframe to store lists totals <- rowSums(df) #Creates rowsum list from df column result[1] <- totals #intended to make totals a column in result. does not work } 谢
doThing <- function(df){
result <- c() #Sets up dataframe to store lists
totals <- rowSums(df) #Creates rowsum list from df column
result[1] <- totals #intended to make totals a column in result. does not work
}
谢谢大家! 您可以将行总和作为新列分配给dataframe
doThing <- function(df){
transform(df, total= rowSums(df))
}
doThing(mtcars)
# mpg cyl disp hp drat wt qsec vs am gear carb total
#Mazda RX4 21.0 6 160.0 110 3.90 2.62 16.5 0 1 4 4 329
#Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.88 17.0 0 1 4 4 330
#Datsun 710 22.8 4 108.0 93 3.85 2.32 18.6 1 1 4 1 260
#Hornet 4 Drive 21.4 6 258.0 110 3.08 3.21 19.4 1 0 3 1 426
#Hornet Sportabout 18.7 8 360.0 175 3.15 3.44 17.0 0 0 3 2 590
#...
#...
doThing我们可以使用
doThing <- function(df) {
df[["total"]] <- rowSums(df)
df
}
doThing(mtcars)
doting结果
doThing <- function(df) {
df[["total"]] <- rowSums(df)
df
}
doThing(mtcars)