y3trgfhsfgr
y3trgfhsfgr

Reputation: 467

calculating length using na.omit in R

here is my code:

data <-setNames(lapply(paste0("80-20 ", file.number,".csv"),read.csv,stringsAsFactors=FALSE),paste(file.number,"participant"))
# imports csv data and turns it into a R-data file

df <- data.frame(RT=1:100,rep.sw=sample(c("sw","rep",100,replace=TRUE)))

(error.sw.c <- lapply(data[control.data],function(df) with(df, na.omit(rep.sw == "sw" & accuracy == "wrong"))))

This code scans a bunch of excel file and attributes a value of 'TRUE' every time the accuracy is "wrong" for values labeled "sw." then what I want to do is count the number of true values, and put them in a data frame. This is what I tried:

(dataframe.c <- data.frame(switch.rt = sapply(sw.c,mean), repetition.rt = sapply(rep.c,mean), switch.error = sapply(error.sw.c,length), group = rep("control",each=length(control.data))))

However, when I do this, it gives me the length of all the values (TRUE & FALSE), not just the TRUE values.

If I do this:

length(error.sw.c)

I get the total of all the error values, not all the error values separately.

So my question is: Is there a way to get the length of each individual excel file so I can put it in a dataframe? Thank you StackOverflow community, you folks haven't let me down yet. Any help will be greatly appreciated. Let me know if any clarification is needed. :)

Upvotes: 1

Views: 171

Answers (1)

nothing
nothing

Reputation: 3290

sum() can be used to count the number of TRUEs in a logical vector. Let's see why:

set.seed(555)
logicalVec <- rnorm(5) > 0 # create logical vector
logicalVec
[1] FALSE  TRUE  TRUE  TRUE FALSE

Arithmetic functions coerce logical values to numeric values such that FALSE becomes 0 and TRUE becomes 1:

logicalVec*1
[1] 0 1 1 1 0

You can think of sum(logicalVec) as equivalent to sum(c(0,1,1,1,0)):

sum(c(0,1,1,1,0))
[1] 3
sum(logicalVec)
[1] 3

Upvotes: 2

Related Questions