我有一个简单的功能:
new_function <- function(x)
{
letters <- c("A","B","C")
new_letters<- c("D","E","F")
if (x %in% letters) {"Correct"}
else if (x %in% new_letters) {"Also Correct"}
else {x}
}
我用字母制作一个dataframe
:
df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
names(df)<- c("Letters")
我想在dataframe
上应用该功能:
df$result <- new_function(df$Letters)
它不起作用(该函数仅写“ Correct”)
我收到此警告:
警告信息: 在if(x%in%个字母){: 条件的长度> 1,并且只会使用第一个元素
答案 0 :(得分:2)
您可以使用lapply
:
df$result <- lapply(df$Letters,new_function)
输出:
df
Letters result
1 A Correct
2 B Correct
3 C Correct
4 D Also Correct
5 E Also Correct
6 F Also Correct
7 G 7
8 H 8
9 I 9
10 J 10
答案 1 :(得分:0)
我会按照@akrun的建议,用new_function
重写您的ifelse
。 as.character
将x
转换为字符,以防万一:
new_function <- function(x){
ifelse(x %in% c("A","B","C"), "Correct",
ifelse(x %in% c("D","E","F"), "Also Correct", as.character(x)))
}
df$result <- new_function(df$Letters)
或与case_when
中的dplyr
一起使用:
library(dplyr)
new_function <- function(x){
case_when(x %in% c("A","B","C") ~ "Correct",
x %in% c("D","E","F") ~ "Also Correct",
TRUE ~ as.character(x))
}
df %>%
mutate(result = new_function(Letters))
结果:
Letters result
1 A Correct
2 B Correct
3 C Correct
4 D Also Correct
5 E Also Correct
6 F Also Correct
7 G G
8 H H
9 I I
10 J J
数据:
df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
names(df)<- c("Letters")