Loop over vector (introspection in R?) Or some other approach

I have a table of tfvalues ​​with column headers formant vowel length IL SG.

This is how I get their values:

f1a <- subset(tf, tf$vowel=='a' & tf$formant=='F1')$IL
f2a <- subset(tf, tf$vowel=='a' & tf$formant=='F2')$IL

f1e <- subset(tf, tf$vowel=='e' & tf$formant=='F1')$IL
f2e <- subset(tf, tf$vowel=='e' & tf$formant=='F2')$IL

Is there a way to rewrite this with a loop for a given vowels <- c('a', 'e', 'i', 'o', 'u')? Or is there a different approach?

Decision: split

Using split, the above can be easily achieved with just one line:

fvowels = split(tf$IL, paste(tolower(tf$formant), tf$vowel, sep=""))

Where:

  • splitDrag and drop data in tf$ILaccordance with the second part of the argument;
  • pasteCombines elements after they are converted to string;
  • tolower changes characters to lower case.

Result in fvowelsis a data set from f1ato f3u.

+3
source share
2 answers

Take a look at split

tf <- data.frame(
  formant = sample(c("F1","F2"), 100, T),
  vowels = sample(c('a', 'e', 'i', 'o', 'u'), 100, T),
  IL = runif(100)
)
split(tf$IL, paste(tolower(tf$formant), tf$vowels, sep=""))

. assign attach , , , (, lapply ).

+3

:

tf <- data.frame(formant=c("F1","F2"),vowel=c('a', 'e', 'i', 'o', 'u'),IL=rnorm(100))

vowel<-c('a', 'e', 'i', 'o', 'u')

:

for (i in vowel){
    assign(paste("F1",i,sep=""),subset(tf, tf$vowel==i & tf$formant=='F1')$IL)
    assign(paste("F2",i,sep=""),subset(tf, tf$vowel==i & tf$formant=='F2')$IL)
}

F1e
F2a

, plyr:

library(plyr)
foo<-dlply(tf,.(formant,vowel),function(x)x$IL)

foo$F1.e
foo$F2.a

, , , :)

+3

Source: https://habr.com/ru/post/1792199/


All Articles