![](/img/trans.png)
[英]How to change the values in several columns of a data frame, when they have the same value in another specific column?
[英]how to change column name in several data frame in the same time?
我有五个具有相同列数的数据框。 我想使用rbind
来附加我的数据,但它们有不同的变量名称。 幸运的是,它具有与此相同的形式。
date prod1 code1 tot1
date prod2 code2 tot2
...
date prod5 code5 tot5
我想同时删除数字代码,这样我就可以绑定我的数据帧了。 我怎样才能做到这一点?
提前致谢。
由于问题是如何更改列名,我将首先解决这个问题:
lapply(dflist, setNames, nm = new_col_name)
df1 <- data.frame(prod1 = 1:5, code1 = 1:5, tot1 = 1:5)
df2 <- data.frame(prod2 = 1:5, code2 = 1:5, tot2 = 1:5)
dflist <- list(df1, df2)
lapply(dflist, setNames, nm = c("prod", "code", "tot"))
[[1]]
prod code tot
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
[[2]]
prod code tot
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
如前所述,最好忽略列名并使用rbindlist
的data.table
来绑定行。
data.table::rbindlist(dflist, use.names = F)
您可以使用magrittr
和dplyr
来做到这dplyr
:
d1 <- mtcars
d2 <- d1
d3 <- d1
names(d2) <- paste0(names(d2), "_2")
names(d3) <- paste0(names(d2), "_3")
rbind(d1, d2, d3) # gives an error, ok
#> Error in match.names(clabs, names(xi)): les noms ne correspondent pas aux noms précédents
library(magrittr, quietly = TRUE, warn.conflicts = FALSE)
library(dplyr, quietly = TRUE, warn.conflicts = FALSE)
df_list <- list(d2, d3)
df_list <- lapply(df_list, magrittr::set_colnames, names(d1))
df_final <- rbind(d1, dplyr::bind_rows(df_list) )
nrow(df_final) == 3* nrow(d1)
#> [1] TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.