r - 将信息添加到有条件地比较字符串的列
问题描述
我有一个名为“草”的数据框。此数据帧中的信息之一是“线”,可以是:高、低、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
谢谢!
解决方案
如何使用该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
推荐阅读
- python - 计算熊猫数据框中两点之间的欧几里得距离
- javascript - Sass:如何不监视 node_modules 的更改
- git - 为什么冲突总是与合并分支有关?
- sql-server - 多数据库访问与加入 2 个表的性能
- reactjs - 使用过滤器返回日期
- python - Pygame:如何让两个物体在碰撞后停止移动
- python - 从数据框中只读取一列
- java - 支持库的 FragmentManager 类型不兼容
- java - 将应用程序部署到 AWS Lambda 会引发 Postgres 驱动程序错误
- python - 如何访问 ImageField 对象并将其显示到模板