Harminder Puri
Harminder Puri

Reputation: 3

Applying if statement to data frame elements

Here is what i am trying to do: 1. Read in csv file 2. Create a column number 107 and copy values from column 67 based on the condition:' only copy values if row values in column 70 is "Yes"'

Code:

report <- read.csv("C:\\Users\\ha317981\\Desktop\\practice\\input.csv",  header=1)
for(i in 1:length(report[[70]])-1){ 
    if(report[[i, 70]] =="Yes"){
      report[[i,107]] <-report[[i, 67]]  
    }
    i<- i + 1
  }

Error: Error in [[.default(col, i, exact = exact) : attempt to select less than one element in get1index

Upvotes: 0

Views: 620

Answers (2)

Karthik Arumugham
Karthik Arumugham

Reputation: 1360

You can replace your code with the vectorised operation as below.

report[,107] <- ifelse(report[,70] == "Yes", report[,67], NA) 

Upvotes: 2

JJEO
JJEO

Reputation: 31

You could also use mutate from the dplyr package paired with ifelse.

From the documentation:

"Mutate adds new variables and preserves existing; transmute drops existing variables."

require(dplyr)
report <- read.csv("C:\\Users\\ha317981\\Desktop\\practice\\input.csv",  header=1)

# mutate(tbl_df, NewColumn = Value, ...)

newReport <- mutate(report, Col107 = ifelse(Col70 == "Yes", Col67, NA))

This will create a new variable in your (presumably?) data frame based on the values of Column 70, where the value will either be copied from Column 67 or NA.

Upvotes: 2

Related Questions