首页 > 解决方案 > 将信息添加到有条件地比较字符串的列

问题描述

我有一个名为“草”的数据框。此数据帧中的信息之一是“线”,可以是:高、低、f1、f2、bl 或 bh。

我创建了一个新列,并希望向该列添加信息,如以下代码所示。

问题是我得到了所有人的“1”,而不仅仅是“高”

#add new column
grass["genome.inherited"] <- NA

#adding information to genome.inherited 
#1 for the high-tolerance parent genotype (high)
#0 for the low-tolerance parent genotype  (low)
#0.5 for the F1 and F2 hybrids (f1) (f2)
#0.25 for the backcross to the low tolerance population (bl)
#0.75 for the backcross to the high tolerance population (bh)

#how I tried to solve the problem
grass$genome.inherited <- if(grass$line == 'high'){
    1
} else if(grass$line == 'low'){
    0
} else if(grass$line == 'bl'){
    0.25
} else if(grass$line == 'bh'){
    0.75
} else {
    0.5
}

正如这里所建议的,head(grass) 的输出

line cube.root.height genome.inherited
high             4.13                1
high             5.36                1
high             4.37                1
high             5.08                1
high             4.85                1
high             5.59                1

谢谢!

标签: r

解决方案


如何使用该match功能。它给出了一个数字,表示一个值在字符向量中的位置,并且也有一个“不匹配”值。

grass$genome.inherited <- c(1, 0, 0.25, 0.75, 0.5)[ 
                        match( grass$line, c( 'high', 'low','bl','bh'), nomatch=5) ]

来自控制台的示例以及要测试的其他行值:

 grass <- read.table(text="line cube.root.height genome.inherited
 high             4.13                1
 high             5.36                2
 low             4.37                1
 high             5.08                1
 junk             4.85                1
 high             5.59                1
 ", head=T)

 grass$genome.inherited <- c(1, 0, 0.25, 0.75, 0.5)[ 
                       match( grass$line, c( 'high', 'low','bl','bh'), nomatch=5) ]
 grass
#----
  line cube.root.height genome.inherited
1 high             4.13              1.0
2 high             5.36              1.0
3  low             4.37              0.0
4 high             5.08              1.0
5 junk             4.85              0.5
6 high             5.59              1.0

推荐阅读