I have following data:

d1    <- c(-10,2,3,4,5,6, NA, NA, NA);
d2    <- c(1,2,3,4,5,6,7, NA, NA); 
d3    <- c(1,2,3,4,5,6,700, 800, 900);
d     <- rbind(d1, d2, d3); d <- data.matrix(d)

I would now like to measure the skewness of each row of d (or each participant). I know about the function skewness(x) of the moments package, however, there seems to be a problem. I tried following code:

for (i in 1:nrow(d)){
skew[i] <- as.numeric(skewness(d[i]))
}

Do you have any idea what can be wrong? Thanks a lot!

有帮助吗?

解决方案

Use apply:

apply(d, 1, skewness, na.rm =TRUE)

A fixed version of your for loop:

skew <- vector("numeric", nrow(d))  # first pre allocate to hold the result
for (i in 1:nrow(d)){
  skew[i] <- skewness(d[i, ], na.rm=TRUE) # your matrix indexing was wrong
}
setNames(skew, rownames(d))  # just for names

Note that your matrix indexing was completely wrong, and as NAs are present in your matrix, you need to set na.rm=TRUE to skip them, read ?skewness. I prefer using apply instead of a for loop, read about ?apply.

其他提示

From the Rfast package, you can use:

colskewness(d)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top