[英]How to change colnames of nested dataframes in a list of lists
I have a list of data frames, the names of which are shown below:我有一个数据框列表,其名称如下所示:
lapply(L2, function(x) {print(names(x))}):
$D1
[1] "TP1.adjPVal" "TP1.Log2FC"
$D2
[1] "TP2.adjPVal" "TP2.Log2FC"
$D3
[1] "TP3.adjPVal" "TP3.Log2FC"
$D7
[1] "TP7.adjPVal" "TP7.Log2FC"
$D14
[1] "TP14.adjPVal" "TP14.Log2FC"
I would like to change all the TP
into D
.我想将所有
TP
更改为D
。
I have tried the following codes from searching stackoverflow but am struggling to reach my goal.我已经通过搜索 stackoverflow 尝试了以下代码,但正在努力实现我的目标。
lapply(L2, function(x) {gsub(x = names(x), pattern = 'TP', replacement = 'D')})
setNames(L2$D1, tp$D1)
lapply(L2, function(x) { colnames(x) <- gsub(x = colnames(x), pattern = 'TP', replacement = 'D')})
Any help in this issue would be most welcome.非常欢迎在这个问题上的任何帮助。
We need to return the x
ie the data.frame.我们需要返回
x
即 data.frame。 In the OP's code, it is only doing the assignment.在 OP 的代码中,它只是在做分配。 Also, as the 'TP' is at the start of the string, can use
^
to specify the start and we don't need gsub
instead use sub
(for single substitution)此外,由于 'TP' 在字符串的开头,可以使用
^
来指定开头,我们不需要gsub
而是使用sub
(用于单个替换)
lapply(L2, function(x) {
colnames(x) <- sub(x = colnames(x), pattern = '^TP', replacement = 'D')
x}
)
Or another option is setNames
.或者另一个选项是
setNames
。 In this case, we can do the assignment on the fly as setNames
internally does the assignment在这种情况下,我们可以动态地进行分配,因为
setNames
内部进行分配
lapply(L2, function(x) setNames(x,
sub(x = colnames(x), pattern = '^TP', replacement = 'D')))
Also, if we use tidyverse
另外,如果我们使用
tidyverse
library(tidyverse)
map(L2, ~ .x %>%
rename_at(vars(starts_with("TP")), ~ str_replace(., "^TP", "D")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.