将 R 中的字符串分成 2 列并导出为 CSV
Separate String in R into 2 columns and export as a CSV
我以前没有真正使用过 R,但我需要将数据从 CSV 中分离出来,将 440 个条目分成 table 中的 2 列。弦长短不一。我想将字符串分成两部分。
一个例子是ACTL6A_S5
。我想要一列中 _
之前的所有内容以及另一列中 _
之后的所有内容,然后再次将其导出为 CSV。是在 for 循环中管理它的最佳方法还是从哪里开始?
目前我已经设法将 CSV 和我想要的列导出到 RStudio 中并显示出来
biological_dataset <-read.csv("Exampledata.csv") #Setting the name of the csv file
#print(biological_dataset) #Printing the data in the csv file
feature_name_example <- as.character(biological_dataset$X[1])
as.character(biological_dataset$X[1:440])
R 输出:
预期结果类似于
Column1 Column2
1 S1 ACTL6A
2 S2 ADAMTS1
如果我没看错的话,下面应该可以达到你想要的效果:
library("tidyr")
fixed <- separate(data = biological_dataset, col = X, into = c("Column1", "Column2"), sep = "_")
write.csv(x = fixed, file = "fixed_dataset.csv")
简而言之,从给定的数据集中取出 X 列,并将其分成两列,并在有下划线时提供名称。
这是一个使用base R
的选项
out <- cbind(biological_dataset, read.table(text = biological_dataset$X,
sep="_", header = FALSE, col.names = c("Column1", "Column2")))
我以前没有真正使用过 R,但我需要将数据从 CSV 中分离出来,将 440 个条目分成 table 中的 2 列。弦长短不一。我想将字符串分成两部分。
一个例子是ACTL6A_S5
。我想要一列中 _
之前的所有内容以及另一列中 _
之后的所有内容,然后再次将其导出为 CSV。是在 for 循环中管理它的最佳方法还是从哪里开始?
目前我已经设法将 CSV 和我想要的列导出到 RStudio 中并显示出来
biological_dataset <-read.csv("Exampledata.csv") #Setting the name of the csv file
#print(biological_dataset) #Printing the data in the csv file
feature_name_example <- as.character(biological_dataset$X[1])
as.character(biological_dataset$X[1:440])
R 输出:
预期结果类似于
Column1 Column2
1 S1 ACTL6A
2 S2 ADAMTS1
如果我没看错的话,下面应该可以达到你想要的效果:
library("tidyr")
fixed <- separate(data = biological_dataset, col = X, into = c("Column1", "Column2"), sep = "_")
write.csv(x = fixed, file = "fixed_dataset.csv")
简而言之,从给定的数据集中取出 X 列,并将其分成两列,并在有下划线时提供名称。
这是一个使用base R
out <- cbind(biological_dataset, read.table(text = biological_dataset$X,
sep="_", header = FALSE, col.names = c("Column1", "Column2")))