简体   繁体   English

如何在以下目标中使用R的重塑:

[英]How to use R's reshape in the following goal:

I am trying to reshape data from wide format to long format. 我正在尝试将数据从宽格式重塑为长格式。 In the following table, I have: 在下表中,我有:

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

As you can see, several samples can have the same string. 如您所见,几个样本可以具有相同的字符串。 The samples are the colnames. 样本是colnames。 I would like to have the following into a vector. 我想将以下内容放入向量中。 I don't want any zero, and I need all the instances of each string: 我不想要任何零,我需要每个字符串的所有实例:

 string1
 string2
 string1
 string3

So far, I wrote the following code: 到目前为止,我编写了以下代码:

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

SV37.refined is the name of my data frame. SV37.refined是我的数据框的名称。 However, I get: 但是,我得到:

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

Do you have any idea? 你有什么主意吗?

Thank you very much for your time! 非常感谢您的宝贵时间!

If its not necessary to use reshape 如果没有必要使用reshape

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

or if you're into one-liners 或者如果你是单行的

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

Using reshape : 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM