[英]How to conditional concatanate in R?
I'm trying to extract some characters from a vector called "identhog" which is allocated in the table "E".我正在尝试从表“E”中分配的名为“identhog”的向量中提取一些字符。 But I want to extract some characters according with its text length.
但我想根据其文本长度提取一些字符。 Then if the lenght of the text in the vector is 10 I want to extract some characters, otherwise I want to extract another characters from another position.
然后如果向量中文本的长度是 10 我想提取一些字符,否则我想从另一个位置提取另一个字符。
if (nchar(E$identhog)==10) {
E <- mutate(E,prueba2= substr(E$identhog, 2, 6))
} else {
E <- mutate(E, prueba2=substr(E$identhog, 3,7))
}
I´m using an IF ELSE conditional, but When I run the code the following message shows up.我使用 IF ELSE 条件,但是当我运行代码时,会显示以下消息。
"Warning message: In if (nchar(E$identhog) == 10) { : the condition has length > 1 and only
the first element will be used"
And R ignores my whole IF conditional and just run: R 忽略我的整个 IF 条件并运行:
E <- mutate(E,prueba2= substr(E$identhog, 2, 6))
How can I fix this?我怎样才能解决这个问题? I have investigated about this problem and it seems that happens because I'm attempting to use an if() function to check for some condition, but it's passing a vector to the if() function instead of individual elements.
我已经调查了这个问题,这似乎是因为我试图使用 if() 函数来检查某些条件,但它正在将向量传递给 if() 函数而不是单个元素。
I understand that R is just checking one element in a vector at one time, but I want to check each individual element.我知道 R 只是一次检查向量中的一个元素,但我想检查每个单独的元素。 Some users tell that the command "ifelse" is a solution, but it is not working with my data for the amount of information it has.
一些用户说命令“ifelse”是一个解决方案,但就其拥有的信息量而言,它无法处理我的数据。
ifelse((nchar(E$identhog)==10),
E <- mutate(E,prueba2= substr(E$identhog, 2, 6)),
E <- mutate(E, prueba2=substr(E$identhog, 3,7)))
Any solution?任何解决方案?
You are using ifelse
outside mutate
, here an example of how to use it with dplyr
.您在
mutate
之外使用ifelse
,这里是一个如何将它与dplyr
一起使用的示例。
library(dplyr)
df <- data.frame(string = c("1234567890","12345678901"))
df %>%
mutate(
prueba2 = if_else(
condition = nchar(string) == 10,
true = substr(string, 2, 6),
false = substr(string, 3, 7)
)
)
string prueba2
1 1234567890 23456
2 12345678901 34567
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.