Rstudent
Rstudent

Reputation: 75

Creating a new column conditional on the character values of two other columns

I am only a learner in R and have a fairly basic question.

I have a dataset called edata with two columns relevant to the posted question. These are GazeCue and TargetLocation. I wish to create a new column called CueType that shows as "Cued" or "Uncued" based on the values of the other two columns.

When GazeCue is equal to RightGazePic1.png and TargetLocation is equal to TargetR, the new CueType column should show as "Cued". Similarly when GazeCue is equal to LeftGazePic1.png and TargetLocation is equal to TargetL, the CueType column should again show as "Cued". Any other variation of values should show in CueType as "uncued".

An example of what I would like is pasted below.

GazeCue                  TargetLocation            CueType         

RightGazePic1.png        TargetR                   Cued             
LeftGazePic1.png         TargetL                   Cued             
RightGazePic1.png        TargetL                   Uncued           
LeftGazePic1.png         TargetR                   Uncued          

I have been trying to complete this code using ifelse but with no luck. Any advice would be greatly appreciated.

Upvotes: 2

Views: 565

Answers (3)

Lorenzo Benassi
Lorenzo Benassi

Reputation: 621

you can try this:

edata[,3] <- NA #add a new column
names(edata)[3] <- "CueType" #add a name column

for (i in 1 : nrow(edata)) {
  if (edata$GazeCue[i] == 'RightGazePic1.png' & edata$TargetLocation[i]==
'TargetR') {
    edata[i,3] <- "Cued"
  } else if (edata$GazeCue[i] == 'LeftGazePic1.png' & data$TargetLocation[i]
=='TargetL') {
    edata[i,3] <- "Cued"
  }
  else {
    edata[i,3] <- "Uncued"
  }
}

Test, it should work properly!

Upvotes: 0

h3rm4n
h3rm4n

Reputation: 4187

You can also make use of the fact that R recycles vectors:

ix <- (substr(df$GazeCue,1,1) == substring(df$TargetLocation,7)) + 1
df$CueType <- c("Uncued","Cued")[ix]

Upvotes: 1

Joris Meys
Joris Meys

Reputation: 108523

This is pretty basic. One way would be to extract the L and R from both the png and the Target, and compare those using ifelse:

CueType <- ifelse(substr(GazeCue, 1,1) == substr(TargetLocation, 7,7),
                  "Cued",
                  "Uncued")

If the names can vary a bit more, take a look at gsub to extract the relevant information from the strings before making the comparison.

Upvotes: 3

Related Questions