If Statement, do function, say statement
I am trying to write a simple if statement. I have data like this
Number Description Type
1 Snow in road "weather"
2 Ice on Roof "Weather"
3 Dog bite "Not Classified"
Basically trying to do this:
if(data$type == "Not Classified") {sapply(data$description, colcheck)} else "Not Classified"
The desired result would be for the function that I have stated previously in my code to run on row 3, the "Not Classified"
row. For some reason, I keep getting the same error:
"Not Classified"
"the condition has length > 1 and only the first element will be used".
colcheck
is a function created previously. I have tried IfElse
, taking out the else
at the end, and adding a do
in front of the function, but they aren't working. I am trying to filter the data to only use the function on the rows where type == "Not classified"
. Thank you
colcheck
IfElse
else
do
type == "Not classified"
data$newColumn <- ifelse(data$type == "Not Classified", colcheck(data$description), "Not Classified")
1 Answer
1
The problem is that data$type
is a vector of length > 1. The ==
operator compares a single value only and when you pass it a vector, it takes only the first value, rather than failing.
data$type
==
What you want to do is use apply
or dplyr::mutate
to apply the test to each element of data$type
:
apply
dplyr::mutate
data$type
data <- data.frame('id' = c(1,2,3,4,5,6),
'type' = rep(c('Classified','Not Classified'),3),
'description' = c('Cat', 'Dog', 'Fish', 'Mouse', 'Horse', "Moose"))
data
id type description
1 1 Classified Cat
2 2 Not Classified Dog
3 3 Classified Fish
4 4 Not Classified Mouse
5 5 Classified Horse
6 6 Not Classified Moose
Example function for colcheck
:
colcheck
colcheck <- function(x) return(paste0('x',x,'x'))
Using base apply
:
apply
apply(data, 1, function(row) {
if (row['type'] == 'Not Classified') {
return(colcheck(row['description']))
} else {
return("Not Classified")
}
})
[1] "Not Classified" "xDogx" "Not Classified" "xMousex" "Not Classified"
[6] "xMoosex"
Or with dplyr
:
dplyr
data %>%
mutate('colcheck' = if_else(type == 'Not Classified',
colcheck(description),
'Not Classified'))
id type description colcheck
1 1 Classified Cat Not Classified
2 2 Not Classified Dog xDogx
3 3 Classified Fish Not Classified
4 4 Not Classified Mouse xMousex
5 5 Classified Horse Not Classified
6 6 Not Classified Moose xMoosex
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Maybe:
data$newColumn <- ifelse(data$type == "Not Classified", colcheck(data$description), "Not Classified")
– zx8754
21 mins ago