遍历向量(R?中的自省)或其他方法 [英] Loop over vector (introspection in R?) or some other approach

查看:138
本文介绍了遍历向量(R?中的自省)或其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表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 in tf$IL according to the second part of the argument;
  • paste joins items after converting them to string;
  • tolower changes characters to lower case.

fvowels中的结果是一组从f1af3u的数据.

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=""))

它为您提供了包含单独数据的命名列表.如果希望将其作为单独的变量,可以将它assignattach放置到全局工作区中,但是我建议使用列表代替(例如,您可以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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆