【问题标题】:How to use R's reshape in the following goal:如何在以下目标中使用 R 的重塑:
【发布时间】:2014-03-17 00:31:59
【问题描述】:

我正在尝试将数据从宽格式重塑为长格式。在下表中,我有:

 Sample 1    Sample 2   Sample 3 ...   Sample 18
 string1     string2    0              String3
 0           string1    0              0
 0           0          0              0

如您所见,多个样本可以具有相同的字符串。样本是列名。我想将以下内容放入向量中。我不想要任何零,我需要每个字符串的所有实例:

 string1
 string2
 string1
 string3

到目前为止,我写了以下代码:

 reshape(SV37.refined, direction="long",varying=names(SV37.refined), v.names="Value", idvar ="Index", times=names(SV37.refined), timevar="Sample")

SV37.refined 是我的数据框的名称。但是,我得到:

1.Sample1   Sample1    string1     1
2.Sample1   Sample1    0           2
3.Sample1   Sample1    0           3
4.Sample2   Sample2    string2     4
5.Sample2   Sample2    string1     5
6.Sample2   Sample2    0           6

你有什么想法吗?

非常感谢您的宝贵时间!

【问题讨论】:

    标签: r reshape


    【解决方案1】:

    如果没有必要使用reshape

    out <- unlist(lapply(SV37.refined, as.character))
    out[out != "0"]
    ##  Sample11  Sample21  Sample22 Sample181 
    ## "string1" "string2" "string1" "string3" 
    

    或者如果你喜欢单线

    Filter(function(x) x != "0", unlist(lapply(SV37.refined, as.character)))
    ##  Sample11  Sample21  Sample22 Sample181 
    ## "string1" "string2" "string1" "string3" 
    

    【讨论】:

    • 很好的答案。我建议只使用 as.character(unlist(SV37.refined)) 来简化它(不需要 lapply)。
    • @Jealie 在变量是因子时尝试一下。您的方法仅在它们已经是字符的情况下才有效,在这种情况下 as.character 根本不需要
    • 你是绝对正确的......我仍在与这些因素作斗争。我在测试中发现c(as.matrix(SV37.refined)) 似乎工作得很好,但是你打电话给lapply 看起来并不好:)
    【解决方案2】:

    使用reshape

    dat <- read.table(text="
    Sample1 Sample2
    string1 string2
    0 string1
    0 0", header=TRUE)
    
    #  Sample1 Sample2
    #1 string1 string2
    #2       0 string1
    #3       0       0
    
    out <- reshape(
      dat,
      varying=c("Sample1","Sample2"),
      direction="long",
      times=1:2,
      v.names="Value",
      timevar="Sample" 
    )
    
    out[out$Value != 0,]
    
    #    Sample   Value id
    #1.1      1 string1  1
    #1.2      2 string2  1
    #2.2      2 string1  2
    

    【讨论】:

    • 非常感谢您的帮助!当我写最后一行时,我得到“找不到对象”。我试了好几次,但总是遇到同样的错误。
    • 哎呀!我忘了加上昏迷! :) 现在效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2023-03-16
    • 2018-05-07
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多