2

比如我有一个这样的数据框(v1的内容和行号不一样):

V1 V2 V3
1 cat animal
3 dog animal
4 apple fruit

像这样的向量:

c(4,1,3)

有没有一种简单的方法可以在 R 中获得这样的向量?

c("fruit:apple", "animal:cat", "animal:dog")

我试过==my_frame$V1==my_vector)但发现不能用于两个向量..

4

6 回答 6

1

像这样的工作:

## my_dat <- read.table(text="V1 V2 V3
## 1 cat animal
## 2 dog animal
## 3 apple fruit", header=T)
## 
## my_vect <- c(3,1,2)

library(qdap)  #for paste2 function
paste2(my_dat[sapply(my_vect, function(x) which(x == my_dat[, 1])), 3:2], sep=":")
## [1] "fruit:apple" "animal:cat"  "animal:dog"

首先,我将与using和my_vect的第 1 列相匹配。这告诉了要抓取的订单:my_datsapplywhich==

sapply(my_vect, function(x) which(x == my_dat[, 1]))
## [1] 3 1 2

然后我按您要求的顺序索引并仅抓取最后两列(第 3 列,然后是第 2 列)

my_dat[sapply(my_vect, function(x) which(x == my_dat[, 1])), 3:2]

##       V3    V2
## 3  fruit apple
## 1 animal   cat
## 2 animal   dog

然后我paste2qdap包中使用将列绑定在一起而不指定特定列(只是懒惰;您可以paste通过显式声明向量来使用 base 来完成此操作。

于 2013-06-03T13:21:33.353 回答
1

@Firegun,如何使用“合并”,如下所示:

#original data frames
df1=data.frame(V1=c(1,3,4),V2=c("cat","dog","apple"),V3=c("animal","animal","fruit"))
df2=data.frame(V1=c(4,1,3))

# just merge and don't sort (which is the default)
df3=merge(df2,df1,by.x="V1",sort=FALSE)
vec=as.vector(paste0(df3$V3,":",df3$V2))

> vec
[1] "fruit:apple" "animal:cat"  "animal:dog"  
于 2013-06-03T15:58:04.177 回答
1

稍微简洁一点的版本:

my_charvec <- as.character(my_vector)
rownames(my_frame) <- my_frame$V1
apply(my_frame[my_charvec,c(3,2)],1,paste,collapse=":")

这是输出:

            4             1             3 
"fruit:apple"  "animal:cat"  "animal:dog"

输出中的 4,1,3 只是名称;如果你愿意,你可以忽略它们。

于 2013-06-03T16:37:06.963 回答
1

另一种基本 R 解决方案,使用matchmapply

d <- read.table(text='V1 V2 V3
1 cat animal
3 dog animal
4 apple fruit', header=TRUE)
v <- c(4,1,3)

with(d[match(v, d$V1), ], paste(V3, V2, sep=':'))
# [1] "fruit:apple" "animal:cat"  "animal:dog" 
于 2013-06-03T16:40:59.910 回答
0

也许是这样的?

> df<-data.frame(V1=c(1,2,3), V2=c("a","b","c"), V3=c("v", "nv", "nv"))
> v <- c(3,1,2)
> df[v,]
##   V1 V2 V3
## 3  3  c nv
## 1  1  a  v
## 2  2  b nv
> res <- as.character(apply(df[v,], 1, function(r) paste(r[3],r[2],sep=":")))
> res
## [1] "nv:c" "v:a"  "nv:b"
于 2013-06-03T13:23:29.867 回答
0

这是一个基本解决方案

a <- data.frame(c("cat", "dog", "apple"), c("animal", "animal", "fruit"))
v <- c(3,1,2)
apply(a[v,], 1, paste0, collapse=":")
于 2013-06-03T13:23:42.613 回答