【问题标题】:Separate String in R into 2 columns and export as a CSV [duplicate]将 R 中的字符串分成 2 列并导出为 CSV [重复]
【发布时间】:2019-10-09 19:11:06
【问题描述】:

我以前没有真正使用过 R,但我需要将 CSV 中的数据与 440 个条目分开到表中的 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

【问题讨论】:

    标签: r string export-to-csv


    【解决方案1】:

    如果我理解正确,以下应该可以实现您想要的:

    library("tidyr")
    fixed <- separate(data = biological_dataset, col = X, into = c("Column1", "Column2"), sep = "_")
    
    write.csv(x = fixed, file = "fixed_dataset.csv")
    

    简而言之,从给定的数据集中取出列 X,并将其分成两列,其中包含下划线时提供的名称。

    【讨论】:

    • 太好了,谢谢
    • 太好了,很高兴它有帮助。您可能应该接受其中一个答案。
    【解决方案2】:

    这是一个使用base R的选项

    out <- cbind(biological_dataset, read.table(text = biological_dataset$X, 
           sep="_", header = FALSE, col.names = c("Column1", "Column2")))
    

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2021-12-28
      • 1970-01-01
      • 2012-10-23
      • 2021-05-23
      • 2017-11-07
      • 1970-01-01
      • 2014-10-13
      • 2022-12-16
      相关资源
      最近更新 更多