[R] Sampling dataframe
Juliet Hannah
juliet.hannah at gmail.com
Sat Nov 28 16:51:01 CET 2009
Here are some options that may help you out. First,
let's put the data in a format that can be cut-and-pasted
into R.
myData <- read.table(textConnection("var1 var2 var3
1 1 1 1
2 3 1 2
3 8 1 3
4 6 1 4
5 10 1 5
6 2 2 1
7 4 2 2
8 6 2 3
9 8 2 4
10 10 2 5"),header=TRUE,row.names=1)
closeAllConnections()
or
use dput
myData <- structure(list(var1 = c(1L, 3L, 8L, 6L, 10L, 2L, 4L, 6L, 8L,
10L), var2 = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), var3 = c(1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L)), .Names = c("var1", "var2",
"var3"), class = "data.frame", row.names = c("1", "2", "3", "4",
"5", "6", "7", "8", "9", "10"))
#Select data where v2=1
select_v2 <- myData[myData$var2==1,]
# sample two rows of select_v2
sampled_v2 <- select_v2[sample(1:nrow(select_v2),2),]
# select rows of var3 not equal to 1
select_v3 <- myData[myData$v3 !=1,]
# ?rbind may also come in useful.
2009/11/25 Ronaldo Reis Júnior <chrysopa at gmail.com>:
> Hi,
>
> I have a table like that:
>
>> datatest
> var1 var2 var3
> 1 1 1 1
> 2 3 1 2
> 3 8 1 3
> 4 6 1 4
> 5 10 1 5
> 6 2 2 1
> 7 4 2 2
> 8 6 2 3
> 9 8 2 4
> 10 10 2 5
>
> I need to create another table based on that with the rules:
>
> take a random sample by var2==1 (2 sample rows for example):
>
> var1 var2 var3
> 1 1 1 1
> 4 6 1 4
>
> in this random sample a get the 1 and 4 value on the var3, now I need to
> complete the table with var1==2 with the lines that var3 are not select on
> var2==1
>
> The resulting table is:
> var1 var2 var3
> 1 1 1 1
> 4 6 1 4
> 7 4 2 2
> 8 6 2 3
> 10 10 2 5
>
> the value 1 and 4 on var3 is not present in the var2==2.
>
> I try several options but without success. take a random value is easy, but I
> cant select the others value excluding the random selected values.
>
> Any help?
>
> Thanks
> Ronaldo
>
>
> --
> 17ª lei - Seu orientador quer que você se torne famoso,
> de modo que ele possa, finalmente, se tornar famoso.
>
> --Herman, I. P. 2007. Following the law. NATURE, Vol 445, p. 228.
> --
>> Prof. Ronaldo Reis Júnior
> | .''`. UNIMONTES/DBG/Lab. Ecologia Comportamental e Computacional
> | : :' : Campus Universitário Prof. Darcy Ribeiro, Vila Mauricéia
> | `. `'` CP: 126, CEP: 39401-089, Montes Claros - MG - Brasil
> | `- Fone: (38) 3229-8192 | ronaldo.reis at unimontes.br | chrysopa at gmail.com
> | http://www.ppgcb.unimontes.br/lecc | ICQ#: 5692561 | LinuxUser#: 205366
> --
> Favor NÃO ENVIAR arquivos do Word ou Powerpoint
> Prefira enviar em PDF, Texto, OpenOffice (ODF), HTML, or RTF.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list