r - How can I use loops for and if -
this illustration dataset
> v1 v2 1 a1 5437 2 a1 5437 3 a1 5437 4 a2 1819 5 a2 1758 6 a2 1212 7 a2 1212 8 a3 1456 i want compute unique values column v2, result be:
a1 1 a2 3 a3 1 i have started write code, don't have thought - how should like:
old_id <- a[1,2] old_art <- a[2,1] (i in nrow(a)){ if (old_id == a[1,i+2] && old_art == a[i+2,1]){ new_id[i] <- old_id[1,i+2] new_art[i] <- } <- i+1 } i know simple solution like:
tapply(a[,2], a[,1], function(t) length(unique(t))) but task utilize loop function - , if
this sounds homework. for loops run through elements in vector on right hand side of in. means for loop increment automatically , don't need i <- i+1.
hence, for loop should this
for (i in 1:nrow(a)) { < code > } # <- + 1 # no need this! notice i in 1:nrow(a) , no i in nrow(a). haven't checked code, forsyntax. remember, for loops functions; so
for (i in 1:3) { print(i) } #[1] 1 #[1] 2 #[1] 3 is same as
`for`(i, 1:3, print(i)) #[1] 1 #[1] 2 #[1] 3 see ?"for".
r loops if-statement for-loop tapply
No comments:
Post a Comment