0

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

Sotos
  • 51,121
  • 6
  • 32
  • 66

2 Answers2

2

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

report[,107] <- ifelse(report[,70] == "Yes", report[,67], NA) 
Richard Telford
  • 9,558
  • 6
  • 38
  • 51
Karthik Arumugham
  • 1,300
  • 1
  • 11
  • 18
2

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.

JJEO
  • 31
  • 4
  • Thanks! :) . Could you also point out what is wrong with my code? – Harminder Puri Feb 18 '17 at 14:35
  • The problem is that your code is trying to create a new column line by line, rather than creating one column that's the same length as the other columns in one statement. Data frames in R need to have all of their columns be the same length (http://stackoverflow.com/questions/9253303/r-dataframe-with-varied-column-lengths). To fix this, you would have to add a column before the `for` loop and _then_ change it's values line by line. You could do this by putting `report$Col107 = NA` before your `for` loop. – JJEO Feb 18 '17 at 17:28