[英]Add column to list of data frames and do incremental addition / Loop through df for simple addition
I have this data frame (actually, a list of those dfs):我有这个数据框(实际上,这些 dfs 的列表):
ALL <- data.frame(x = 1:3, y = c("a", "b", "c"))
I want to add a column which adds up a certain value until the end of the data frame, like this: 0 + 0.05 = 0.05, 0.05 + 0.05 = 0.1, 0.1 + 0.05 = 0.15 and so on.我想添加一个列,该列将某个值加起来直到数据框的末尾,如下所示:0 + 0.05 = 0.05、0.05 + 0.05 = 0.1、0.1 + 0.05 = 0.15 等等。
So, in my example the result would be所以,在我的例子中,结果是
ALL <- data.frame(x = 1:3, y = c("a", "b", "c"), z=(0,0.05,0.1)
I guess the way to go would be using cbind with lapply (assuming ALL is a list of dfs): ALL<- lapply(ALL, function(x) cbind(x, z = ???))我想要走的路是将 cbind 与 lapply 一起使用(假设 ALL 是 dfs 列表): ALL<- lapply(ALL, function(x) cbind(x, z = ???))
But my brain simple doesn't come up with the right formula for z.但是我的大脑很简单并没有想出正确的 z 公式。
Your help is very appreciated.非常感谢您的帮助。
Greetings你好
trumfnator喇叭
We can use transform
to add new column with seq
to generate the sequence.我们可以使用
transform
添加带有seq
新列来生成序列。
lapply(list_df, function(df) transform(df, z = seq(0, by = 0.05, length.out = nrow(df))))
#[[1]]
# x y z
#1 1 a 0.00
#2 2 b 0.05
#3 3 c 0.10
#[[2]]
# x y z
#1 1 a 0.00
#2 2 b 0.05
#3 3 c 0.10
#4 4 d 0.15
In tidyverse
we can do the same by在
tidyverse
我们可以通过
library(dplyr)
library(purrr)
map(list_df, ~.x %>% mutate(z = seq(0, by = 0.05, length.out = n())))
data数据
ALL <- data.frame(x = 1:3, y = c("a", "b", "c"))
ALL1 <- data.frame(x = 1:4, y = c("a", "b", "c", "d"))
list_df <- list(ALL, ALL1)
也许这就是你想要的
ALL$z <- 0.05*(0:(nrow(ALL)-1))
We can do an assignment and then return the dataset我们可以做一个赋值然后返回数据集
lapply(list_df, function(x) {x$z <- seq(0, by= 0.05, length.out = nrow(x));x})
ALL <- data.frame(x = 1:3, y = c("a", "b", "c"))
ALL1 <- data.frame(x = 1:4, y = c("a", "b", "c", "d"))
list_df <- list(ALL, ALL1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.