jackson883 jackson883 - 1 year ago 78
R Question

how to select subset only by [] in r?


I want to convert the element of
,and I want to use only
.I believe all the subset can be done by [].


but it doesn't work, what's the problem?

Answer Source

We create the a numeric index of the column names that start with 'q' followed by numbers ('nm1'), use that to subset the columns in 'a' and assign the values that are not equal to 1 in that subset to 0.

nm1 <- grep("q\\d+", names(a))
a[nm1][a[nm1] != 1] <- 0

and make sure we have the columns as character class by using stringsAsFactors= FALSE in the data.frame

The above replacement is based on a logical matrix (a[nm1]!=1) which may create memory problems if the dataset is really big. In that case, it is better to loop through the columns and replace with 0

a[nm1] <- lapply(a[nm1], function(x) replace(x, x!=1, 0))


a <- data.frame(q1=rep(c(1,'A','B'),4),q2=c(1,'A','B','C'),
                 w1=c(1,'A','B','C'), stringsAsFactors=FALSE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download