R使用ifelse语句,当条件为true时如何从另一列中提取值?

时间:2018-09-13 09:12:10

标签: r dataframe if-statement

可能有一个简单的解决方案,但是我整夜都在努力地获得它,并且找不到合适的搜索词来找到答案,因此,我感谢您的帮助。

本质上,我正在通过查找不同dataframe2中的行的名称来填充新的dataframe,如果该名称在dataframe2中,那么我想将其值拉入datagrame2的第二列...不是,那我想加一个零。

这是我有的代码..但是,如果名称在dataframe2中,则这是随机提取值。

UTR3s.totes.df <- UTR3s.df
for (i in 1:317) {
  targets.df <- subset(TC_merge,V14==consmiRNAs[i])[,c(18,5)]
  targets <- intersect(targets.df$ENSEMBL, UTR3s$Gene)
  targets.df <- subset(targets.df, targets.df$ENSEMBL %in% targets)
  sitenumber = data.frame(Gene = UTR3s$Gene)
  UTR3s.totes.df[, paste("target",i,sep="")] <- ifelse(sitenumber$Gene %in% 
targets.df$ENSEMBL, targets.df$V5, "0")
}

除最后一行外,其他所有东西都在工作……从dataframe2(targets.df)中提取相应的值

可复制的示例已添加:

U.df <- data.frame(name=c("name1","name2","name3","name4","name5"))
targets.df <- data.frame(name=c("name1","name3","name5"),value=c(2,1,3))
U.df[, paste("target",i,sep="")] <- ifelse(U.df$name %in% targets.df$name, 
targets.df$value, "0")

1 个答案:

答案 0 :(得分:0)

您可以尝试以下2种选择:

## data
U.df <- data.frame(name=c("name1","name2","name3","name4","name5"))
targets.df <- data.frame(name=c("name1","name3","name5"),value=c(2,1,3))

## option 1 (based on merging the data frames)
library(dplyr)
U.df2 <- left_join(U.df, targets.df, by = "name")
U.df2$value[is.na(U.df2$value)] <- 0 # set NA values to 0
U.df2 # output
   name value
1 name1     2
2 name2     0
3 name3     1
4 name4     0
5 name5     3

## option 2 (if you only want an ifelse statement)
U.df$value <- ifelse(U.df$name %in% targets.df$name,
                     targets.df$value[match(U.df$name, targets.df$name)],
                     0)
U.df # output
   name value
1 name1     2
2 name2     0
3 name3     1
4 name4     0
5 name5     3