替换特定列“单词”进入数字或空白
输入表
Patients Hospital Drug Response
1 AAA a Good
1 AAA a Bad
2 BBB a Bad
3 CCC b Good
4 CCC c Bad
5 DDD e undefined
输出文件
Patients Hospital Drug Response
1 AAA a 1
1 AAA a -1
2 BBB a -1
3 CCC b 1
4 CCC c -1
5 DDD e
如何将一列中的3个文本替换为数字和空白?
将“响应栏中的良好”改为“1” 将“响应列中的错误”更改为“-1” “响应列中未定义”到“”
数据:
structure(list(Patients = c(1L, 1L, 2L, 3L, 4L, 5L), Hospital = structure(c(1L,
1L, 2L, 3L, 3L, 4L), .Label = c("AAA", "BBB", "CCC", "DDD"), class = "factor"),
Drug = structure(c(1L, 1L, 1L, 2L, 3L, 4L), .Label = c("a",
"b", "c", "e"), class = "factor"), Response = structure(c(2L,
1L, 1L, 2L, 1L, 3L), .Label = c("Bad", "Good", "undefined"
), class = "factor")), .Names = c("Patients", "Hospital",
"Drug", "Response"), class = "data.frame", row.names = c(NA,
-6L))
Input table
Patients Hospital Drug Response
1 AAA a Good
1 AAA a Bad
2 BBB a Bad
3 CCC b Good
4 CCC c Bad
5 DDD e undefined
Output file
Patients Hospital Drug Response
1 AAA a 1
1 AAA a -1
2 BBB a -1
3 CCC b 1
4 CCC c -1
5 DDD e
How to replace 3 texts in one column to number and blank?
"good in Reponse column" to "1"
"bad in Reponse column" to "-1"
"undefined in Reponse column" to " "
Data:
structure(list(Patients = c(1L, 1L, 2L, 3L, 4L, 5L), Hospital = structure(c(1L,
1L, 2L, 3L, 3L, 4L), .Label = c("AAA", "BBB", "CCC", "DDD"), class = "factor"),
Drug = structure(c(1L, 1L, 1L, 2L, 3L, 4L), .Label = c("a",
"b", "c", "e"), class = "factor"), Response = structure(c(2L,
1L, 1L, 2L, 1L, 3L), .Label = c("Bad", "Good", "undefined"
), class = "factor")), .Names = c("Patients", "Hospital",
"Drug", "Response"), class = "data.frame", row.names = c(NA,
-6L))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过更改因子
Response
的标签来用一行完成此操作:You can do this with one line by changing the labels of the factor
Response
:凯瑟琳,你的问题仍然可以通过一本非常基本的 R 教科书来回答。请参阅德克在你的 上一个问题。
回答
如果
d
是您的数据框,那么:我猜测(我可能是错的)“未定义”缺少数据。在这种情况下,请使用
NA
而不是空白。任何 R 基础书籍都会描述NA
Catherine, your questions could still be answered by a very basic textbook in R. Please see Dirk's comment in your previous question.
Answer
If
d
is your data frame, then:I'm guessing (I may be wrong) that "Undefined" is missing data. In which case, use
NA
rather than a blank. Any basic R book will describeNA
's如果您的数据位于数据框中
df
If your data is in a data frame
df
您可以使用简单的
ifelse()
语句。You can use a simple
ifelse()
statement.