【发布时间】:2020-10-07 01:54:27
【问题描述】:
我有一个带有 ID 号、性别和年龄的 data.frame。我想创建一个基于性别和年龄的分数列。首先我想给所有男性打 1 分,M
ID Sex Age sex_score
1 M 72 1
2 M 65 1
3 F 55 0
我尝试过使用for 循环和sapply,但我仍然是初学者,并不真正知道如何使用它们。这些是我的尝试:
sex_score <- for (i in 1:nrow(df)) {if (df$Sex == "M") {1} else {0}}
我收到警告
In if (eligible$Sex == "M") {... :
the condition has length > 1 and only the first element will be used
我也试过
Sex_score <- sapply(df,function(x)if (df$Sex == "M") {1} else {0})
我收到同样的警告。
【问题讨论】: