如何在R中重命名for循环下的列?
在我的文件夹里有一堆文件,文件名是这样的如何在R中重命名for循环下的列?,r,R,在我的文件夹里有一堆文件,文件名是这样的 GSM123445_samples_table.txt GSM129995_samples_table.txt ... ... GSM129999_samples_table.txt 在每个文件中,表都是这种模式 Identifier VALUE 10001 0.12323 10002 0.11535 为了创建一个只包含我想要的信息的数据框,我使用一个列表遍历文件夹来选择我想要的文件并读取文件表 我希望我的数据框看
GSM123445_samples_table.txt
GSM129995_samples_table.txt
...
...
GSM129999_samples_table.txt
在每个文件中,表都是这种模式
Identifier VALUE
10001 0.12323
10002 0.11535
为了创建一个只包含我想要的信息的数据框,我使用一个列表遍历文件夹来选择我想要的文件并读取文件表
我希望我的数据框看起来像这样
Identifier GSM123445 GSM129995 GSM129999 GSM130095
1 10001 0.12323 0.14523 0.22387 0.56233
2 10002 0.11535 0.39048 0.23437 -0.12323
3 10006 0.12323 0.35634 0.12237 -0.12889
4 10008 0.11535 0.23454 0.21227 0.90098
Identifier x.x x.y x.x x.y
1 10001 0.12323 0.14523 0.22387 0.56233
2 10002 0.11535 0.39048 0.23437 -0.12323
这是我的密码
library(dplyr)
for (file in file_list){
if (!exists("dataset")){ # if dataset not exists, create one
dataset <- read.table(file, header=TRUE, sep="\t") #read txt file from folder
x <- unlist(strsplit(file, "_"))[1] # extract the GSMxxxxxx from the name of files
dataset <- rename(dataset, x = VALUE) # rename the column
}
else {
temp_dataset <- read.table(file, header=TRUE, sep="\t") # read file
x <- unlist(strsplit(file, "_"))[1]
temp_dataset <- rename(temp_dataset, x = VALUE)
dataset<-left_join(dataset, temp_dataset, "Reporter.Identifier")
rm(temp_dataset)
}
}
显然,重命名部分失败了
我怎样才能解决这个问题 问题在于
rename(dataset,x=VALUE)
使用x
作为列名,而不是变量x
的值。解决此问题的一种方法是不使用重命名
,而是连接x
中的列名集合,然后在末尾使用colnames
设置数据集
的列名:
library(dplyr)
x <- "Identifier" ## This will hold all column names
for (file in file_list){
if (!exists("dataset")){ # if dataset not exists, create one
dataset <- read.table(file, header=TRUE, sep="\t") #read txt file from folder
x <- c(x, unlist(strsplit(file, "_"))[1]) # extract the GSMxxxxxx from the name of files can append it to x
}
else {
temp_dataset <- read.table(file, header=TRUE, sep="\t") # read file
x <- c(x, unlist(strsplit(file, "_"))[1])
dataset<-left_join(dataset, temp_dataset, "Reporter.Identifier")
rm(temp_dataset)
}
}
colnames(dataset) <- x
库(dplyr)
x问题在于rename(dataset,x=VALUE)
使用x
作为列名,而不是变量x
的值。解决此问题的一种方法是不使用重命名
,而是连接x
中的列名集合,然后在末尾使用colnames
设置数据集
的列名:
library(dplyr)
x <- "Identifier" ## This will hold all column names
for (file in file_list){
if (!exists("dataset")){ # if dataset not exists, create one
dataset <- read.table(file, header=TRUE, sep="\t") #read txt file from folder
x <- c(x, unlist(strsplit(file, "_"))[1]) # extract the GSMxxxxxx from the name of files can append it to x
}
else {
temp_dataset <- read.table(file, header=TRUE, sep="\t") # read file
x <- c(x, unlist(strsplit(file, "_"))[1])
dataset<-left_join(dataset, temp_dataset, "Reporter.Identifier")
rm(temp_dataset)
}
}
colnames(dataset) <- x
库(dplyr)
x您需要标准评估重命名
而不是非标准评估重命名
。您需要标准评估重命名
而不是非标准评估重命名
。