-2

From a given data frame with a column State which has values P or F I am trying to create another column State1 which will have values 1 or 0 depending on whether State is P or F. The following is the code I wrote

for(i in 1:nrow(df)){
    if (df$State(i)==P) {df$State1(i)<- 1} 
    else {df$State1(i) <- 0}  
    }

However I keep getting the error "attempt to apply non function". My code seems very simple and I am not sure why I am getting non function error. Please help Thanks KS

2
  • try the line df$State(1) - what does it give you? Commented Oct 6, 2016 at 1:51
  • 1
    You are getting this error because parenthesis are used for functions in R. So the syntax "df$State(i)" suggests that df$State is a function that you are calling with the arguments i. Commented Oct 6, 2016 at 2:51

2 Answers 2

1

Your syntax is not correct. Should be:

for(i in 1:nrow(df)){
    if (df$State[i]=="P") {df$State1[i] <- 1} 
    else {df$State1[i] <- 0}  
}
Sign up to request clarification or add additional context in comments.

Comments

0

Fridolin Linder provided the correct syntax. You can also do this with a much shorter command using the ifelse function that is vectorized

df$State1 <- ifelse(df$State == "P", 1, 0)

2 Comments

Or just df$State == "P" should be fine or at least as.integer(df$State == "P")
Yeah but that's a bit of a hack that doesn't generalize very well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.