遍历向量(R?中的自省)或其他方法 [英] Loop over vector (introspection in R?) or some other approach
问题描述
我有一个表tf
的值,其列标题为formant vowel length IL SG
.
I have a table tf
of values with column headings 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
有没有一种方法可以用给定的vowels <- c('a', 'e', 'i', 'o', 'u')
循环来重写它?还是有其他方法?
Is there a way to rewrite this with a loop for a given vowels <- c('a', 'e', 'i', 'o', 'u')
? Or is there some other approach?
使用split
,只需一行即可轻松实现以上目标:
By using split
, the above can easily be achieved by one line only:
fvowels = split(tf$IL, paste(tolower(tf$formant), tf$vowel, sep=""))
位置:
-
split
根据参数的第二部分重新排列tf$IL
中的数据; -
paste
将项目转换为string
后加入; -
tolower
将字符更改为小写.
split
reshuffles data intf$IL
according to the second part of the argument;paste
joins items after converting them tostring
;tolower
changes characters to lower case.
fvowels
中的结果是一组从f1a
到f3u
的数据.
The result in fvowels
is a set of data from f1a
to f3u
.
推荐答案
看看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
在列表上方或轻松保存它).
It gives you named list with separated data. You could assign
or attach
it to global workspace if you want it as separated variables, but I recommend using list instead (you could e.g. lapply
over list or save it easily).
这篇关于遍历向量(R?中的自省)或其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!