[R] replacing values of matrix with random values of another dataframe

Sarah Goslee sarah.goslee at gmail.com
Mon Jun 11 23:32:46 CEST 2012


Hi Curtis,

This isn't quite a reproducible example, though very close. As far as
I can tell, you're over-thinking it.

Instead of:
bengood1=ifelse(search_strat_good==1,sample(m_good_D1,replace=F),search_strat_good)

bengood1 <- search_strat_good
bengood1[bengood1 == 1] <- sample(m_good_D1, size=sum(bengood1 == 1),
replace=FALSE)

I made a couple other comments inline:

On Mon, Jun 11, 2012 at 3:44 PM, Curtis Burkhalter
<curtisburkhalter at gmail.com> wrote:
> Hello,
>
> I'm having trouble performing a certain function within R and I was hoping
> someone might be able to help.  I have a matrix (1000x21) that contains
> whole-number values ranging from 1-7 and I want to replace all entries
> within this matrix that have a value of 1 with a random number contained
> within a different dataframe that has 21 rows,1000 columns.  I've tried
> using the if/else function, but this always seems to return a list with
> strange output.  I've also tried using the "replace" and "apply" functions,
> but can't seem to get anything to work. My code is as follows:
>
> #create data frame of 21000 random values
>
> m_good_initial=rnorm(21000,2.79,0.18)
> m_good_D1=ifelse(m_good_initial<0,0,m_good_initial)

Again, you don't need the ifelse:
m_good_D1 <- m_good_initial
m_good_D1[m_good_D1 < 0] <- 0

> m_good_D1mat=matrix(m_good_D1,byrow=T,21)
> m_good_D1=as.data.frame(m_good_D1mat)
>
> #create matrix of (1000x21) that contains whole-number values ranging from
> 1-7
> #using sample to select values with a respective probability
> search_strat_good <-
> sample(landscenarios,1000,replace=T,prob=com_avgpgood[1,])
> for (i in 2:21) {
>
>        search_strat_good <-
> cbind(search_strat_good,sample(landscenarios,1000,replace=T,prob=com_avgpgood[i,]))
> }

Using cbind is a lot less efficient than creating a matrix of the
desired size beforehand and filling in each column.

Neater yet:
search_strat_good <- sapply(1:21,
function(i)sample(landscenarios,1000,replace=T,prob=com_avgpgood[i,]))

> #replace all search strategies of value "1" within matrix
> "search_strat_good"
> #with a random value from dataframe "m_good_D1"
>
> bengood1=ifelse(search_strat_good==1,sample(m_good_D1,replace=F),search_strat_good)
>
> Any help would be greatly appreciated.
> --
> Curtis Burkhalter
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list