Reputation: 27
I have a large set of data for which I have a list of data frames based on names of stations and I wish to create a new column with numerical values based on a rows checkout name and return name. A sample of the data is shown below:
fz$'66th & Center'
Bike CheckoutKioskName ReturnKioskName
24583 191 66th & Center 66th & Center
24584 191 66th & Center 66th & Center
24585 191 66th & Center 66th & Center
24586 191 66th & Center 66th & Center
24587 191 66th & Center 66th & Center
24588 191 66th & Center 66th & Center
24589 11 66th & Center 66th & Center
24590 11 66th & Center 66th & Center
24591 11 66th & Center 66th & Center
24592 11 66th & Center 66th & Center'
I want to create a new column named 'count' based on if the CheckoutKioskName is the same as ReturnKioskName then the count value should be 0, if the CheckoutKioskName isn't the same as the list value name ('66th & Center' in this case) then the count value should be -1, and the last option is if the ReturnKioskName isn't the same as the list value name then the count value should be 1. My attempt at doing this is below in the if else statements. I keep getting errors when using it either when the columns are factors or when the columns are characters.
if(test$CheckoutKioskName == test$ReturnKioskName){
test$count <- 0
}else{
if(test$ReturnKioskName != t){
test$count <- -1
}else{
if(test$CheckoutKioskName != t){
test$count <- 1
}
}
}
I want to think there is a way to use lapply to complete this task but I continue to fail whenever I use it here.
I appreciate any help I can get.
Upvotes: 1
Views: 51
Reputation: 887118
We can use lapply
lapply(names(fz), function(nm) {fz1 <- fz[[nm]]
transform(fz1, Count = ifelse(CheckoutKioskName == ReturnKioskName, 0,
ifelse(CheckoutKioskName ! = rep(nm, nrow(fz1)), -1, 1)))})
Upvotes: 1
Reputation: 11
Try going via which statements and store your flags in your new column. I recommend converting the tested columns to character, but then couldn't try if that makes a difference, because I don't have time to recreate your data ;)
test$count[which(test$CheckoutKioskName == test$ReturnKioskName)] <- 0
...and so on. Should do the trick.
Upvotes: 0