[R] R Beginner : Loop and adding row to dataframe

Henrik Singmann henrik.singmann at psychologie.uni-freiburg.de
Sun Jul 22 22:54:13 CEST 2012


Hi Phil,

I think you want:

merge(listA, listB, by = "NACE")

which will give you:
   NACE Name aaa bbb ccc
1    1    a   a   a   c
2    1    a   a   a   c
3    1    a   a   a   c
4    2    b   a   a   c
5    2    b   a   a   c
6    3    c   a   a   c

If you want to get rid of the Name column, the following should help:
> tmp <- merge(listA, listB, by = "NACE")
> tmp[,-2]
   NACE aaa bbb ccc
1    1   a   a   c
2    1   a   a   c
3    1   a   a   c
4    2   a   a   c
5    2   a   a   c
6    3   a   a   c

Cheers,
Henrik


Am 22.07.2012 18:35, schrieb ph!l:
> Hi everybody,
>
> I am currently quite inexperienced with R.
> I try to create a function that simply take a value in a dataframe, look for
> this value in another dataframe and copy all the row that have this value
> This example is a simplified version of what I am doing but it's enough to
> help me
>
> listA
> Name NACE
> a 1
> b 2
> c 3
>
> ListB
> NACE aaa bbb ccc
> 1 a a c
> 1 a a c
> 1 a a c
> 2 a a c
> 2 a a c
> 3 a a c
> 4 a a c
> 4 a a c
> 4 a a c
>
> The output i would like to have
> NACE aaa bbb ccc
> 1 a a c
> 1 a a c
> 1 a a c
> 2 a a c
> 2 a a c
> 3 a a c
>
> Code:
>
> listpeer <- function (x) {
>    for (i in 1:length(listA$NACE))
>      TriNACE[i] <- subset.data.frame(ListB, NACE == NACEsample$NACE[i],)
>      TriNACE
> }
>
> But the result is
> Warning message:
> In `[<-.data.frame`(`*tmp*`, i, value = list(NACE = c(3L, 3L, 3L :
> provided xx variables to replace x variables"
> I guess there is something wrong "TriNACE[i]", instead i should use
> something to add rows, but I really don't find anything ?
> Somebody has any clue ?
>
> Thank you for your time and help!
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/R-Beginner-Loop-and-adding-row-to-dataframe-tp4637360.html
> Sent from the R help mailing list archive at Nabble.com.
>

-- 
Dipl. Psych. Henrik Singmann
PhD Student
Albert-Ludwigs-Universität Freiburg, Germany
http://www.psychologie.uni-freiburg.de/Members/singmann



More information about the R-help mailing list