2014-05-21 25 views
1

你好,我对R很新,我想解决可能很简单的问题。 所以,在这里它是:列匹配,并从不同列中获得总和

c1 c2 c3 c4 
a 8 f 5 
b 9 c 4 
c 7 b 3 
d 5 a 2 
e 1 d 5 
f 5 e 4 

我想匹配列C1和C3,并得到总的C2和C4 所以答案应该像

a 10 
b 12 
c 11 
... 

我已经使用匹配函数来获取比赛2列之间,我知道了,但我不知道如何从其他列中得到总数

请帮助我,这只是一个例子,但如果工程,我可以解决我的测序数据。

谢谢。

+0

这些列在一个data.frame中还是单独的data.frames? –

回答

2

你可以尝试这样的:

## Your data.frame 
df <- data.frame(c1=letters[1:6], c2=c(8,9,7,5,1,5), 
       c3=c("f", "c", "b", "a", "d", "e"), c4=c(5,4,3,2,5,4)) 

## Match the indices of column 1 to column 3 
m <- match(df$c1, df$c3) 

## Sum columns 2 and 4, where 4 is rearanged to match column 1 
data.frame(c1 = df$c1, ans = df$c2 + df$c4[m]) 

## c1 ans 
## 1 a 10 
## 2 b 12 
## 3 c 11 
## 4 d 10 
## 5 e 5 
## 6 f 10 

希望它能帮助,

亚历

1

这可能不是最有效的方式,但它应该工作:

# Split the data into two frames 
temp1 = data.frame(a=data$a, b=data$b) 
temp2 = data.frame(c=data$c, d=data$d) 

#Now merge them based on the 'a' and 'c' columns 
out = merge(temp1,temp2, by.x='a', by.y='c') 

#Now we can sum the 'b' and 'd' columns 
out$sum = out$b+out$d 

这应该给你你想要的?

1

这也可以工作

#sample data 
dd<-data.frame(
    c1 = c("a", "b", "c", "d", "e", "f"), 
    c2 = c(8L, 9L, 7L, 5L, 1L, 5L), 
    c3 = c("f", "c", "b", "a", "d", "e"), 
    c4 = c(5L, 4L, 3L, 2L, 5L, 4L) 
) 

#stopifnot(levels(dd$c1)=levels(dd$c3)) 

sums <- with(dd, c2[order(c1)]+c4[order(c3)]) 

基本上你只诉诸c2c4所以他们是为了对应配对的因素,再横越加。

0

这里有一个建议,但它只会在c1和c3的元素都是唯一的时才起作用。如果是这种情况,您可以使用which()功能。像这样:c2[which(c1 == x)] + c4[which(c3) == x]会给你c1的值为c1时x的值和c3的值时c3的值的总和。