R 函数与IF-ELSE不匹配';行不通
我有一个简单的功能:R 函数与IF-ELSE不匹配';行不通,r,function,if-statement,R,Function,If Statement,我有一个简单的功能: 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} } 我想在数据帧上应用该函数: df$result <- new_function(d
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}
}
我想在数据帧上应用该函数:
df$result <- new_function(df$Letters)
df$result您可以使用lappy
:
df$result <- lapply(df$Letters,new_function)
您可以使用lappy
:
df$result <- lapply(df$Letters,new_function)
我会按照@akrun的建议,用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)
结果:
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")
数据:
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")
df我会按照@akrun的建议,用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)
结果:
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")
数据:
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")
df如果长度大于1,则使用ifelse
而不是If/else
并且If语句将评估括号之间的部分是否为真。如果将字母向量传递给If(x%单位为%letters){“Correct”}
,则将返回TRUE
和FALSE
值的向量。每封信都有一个。@ Soren Stilling Christensen:当有人回答你的问题时,请考虑投票或接受答案。如果长度大于1,请使用<代码> IFE/<代码>,而不是<代码> I/EX/CODE >,如果语句将评估括号之间的部分是否为真。如果将字母向量传递给If(x%单位为%letters){“Correct”}
,则将返回TRUE
和FALSE
值的向量。每封信都有一封信。Soren Stilling Christensen:当有人回答你的问题时,请考虑赞成或接受这个答案。