2

我正在尝试在 r 中创建一个 id 虚拟对象。情况有点棘手。如果 id = 15 的长度,我想设置 id1=1,如果长度 =11,我想设置 0(这是唯一的两种情况)。我尝试了以下代码:

id1 <- ifelse(nchar(as.character(data$id) == "15"), 1,0)

代码可以运行,但是当我查看数据时,我发现生成的所有值都是 1 而不是 0,1。换句话说,我怀疑 ifelse 函数的设置有问题。

我也试过这个:

id1 <- factor(ifelse(nchar(as.character(data$id) == "15"), 1,0))

仍然得到相同的结果。

任何人都可以帮我解决这个问题吗?

数据是这样的:

id
799679d656c
032a71ce6132f38
b89602494f78508
c817fdde8fd
74e69d6b574
37d4c1ad5e56d06
63d89a0171f
c8bdb87cd537472
bdc09ee5421b1ec
967f47694e6
e4d825005b1
0eb6b851bba
9b27fa6949aaa42
bc82516f141
c4c7f10be01
cb90e05f8a4
cb45e5a890e
a93f57b965d78eb
5e3bb4f29457d75
62aa2cb20a30e07
33e8f2cd8bd
fdecbac8b827917
b51ea777c53d720
4

1 回答 1

3

没有明确的ifelse声明:

id1 <- (nchar(as.character(data$id)) == 15)+0L

This works because thanks to the brevity of R code, the comparison operator == tests the equality of the two sides without using if, or else. The if statement is implied in the test, replacing a potentially verbose programming task to one concisely executed in R. (credit @DavidArenburg for the zero addition)

The direct fix to your code as mentioned in the comments from user20650:

id1 <- ifelse(nchar(as.character(data$id)) == 15, 1,0)

Results

id1
 #[1] 0 1 1 0 0 1 0 1 1 0 0 0 1 0 0 0 0 1 1 1 0 1 1
于 2015-06-28T20:22:29.337 回答