Uli Kleinwechter
2010-Jan-15 08:10 UTC
[R] Replacing NAs with 0 for variables with the same ending
Dear all, I'm looking for a way to replace NA's with 0 for a number of variables which share the same ending and which constitute a subset of a data frame. Say, for example, there is> data <- data.frame(ax=c(1,2,3,NA,0) , bx=c(3,5,NA,5,1) ,ay=c(5,NA,2,NA,0) , by=c(4,2,NA,2,1))> dataax bx ay by 1 1 3 5 4 2 2 5 NA 2 3 3 NA 2 NA 4 NA 5 NA 2 5 0 1 0 1 I wish to apply something like // // /> data[is.na(data)] <- 0/ // but not to the entire data frame, rather only to the variables ending with x. There should be something which emulates the use of a wildcard, ie. which makes the operation being carried out for all variables "*x". I tried with grep and glob2rx but did not succeed. Many thanks for any hints! Uli Kleinwechter -- Uli Kleinwechter Agricultural and Food Policy Group (420a) Faculty of Agricultural Sciences University of Hohenheim D-70593 Stuttgart Phone: (+49) 711 459-22656 Fax: (+49) 711 459-23752 E-mail: u.kleinwechter at uni-hohenheim.de http://www.uni-hohenheim.de/apo
Jim Lemon
2010-Jan-15 20:51 UTC
[R] Replacing NAs with 0 for variables with the same ending
On 01/15/2010 07:10 PM, Uli Kleinwechter wrote:> Dear all, > > I'm looking for a way to replace NA's with 0 for a number of variables > which share the same ending and which constitute a subset of a data frame. > > Say, for example, there is > >> data<- data.frame(ax=c(1,2,3,NA,0) , bx=c(3,5,NA,5,1) , > ay=c(5,NA,2,NA,0) , by=c(4,2,NA,2,1)) >> data > ax bx ay by > 1 1 3 5 4 > 2 2 5 NA 2 > 3 3 NA 2 NA > 4 NA 5 NA 2 > 5 0 1 0 1 > > I wish to apply something like // > // > /> data[is.na(data)]<- 0/ > // > but not to the entire data frame, rather only to the variables ending > with x. >Hi Uli, How about: data[,grep("x",names(data))][is.na(data[,grep("x",names(data))])]<-0 Jim
Possibly Parallel Threads
- Optimization problem with nonlinear constraint
- Extracting coefficients' standard errors from linear model
- Creating plots for all variables in a data frame and printing them with the variable name in the main title
- Error when producing multiple graphes
- for parameter 'keep' in 'step'