对于 R 数据框中的每一行 [英] For each row in an R dataframe

查看:40
本文介绍了对于 R 数据框中的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,对于该数据框中的每一行,我必须进行一些复杂的查找并将一些数据附加到文件中.

I have a dataframe, and for each row in that dataframe I have to do some complicated lookups and append some data to a file.

dataFrame 包含生物学研究中使用的 96 孔板中选定孔的科学结果,因此我想做如下操作:

The dataFrame contains scientific results for selected wells from 96 well plates used in biological research so I want to do something like:

for (well in dataFrame) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}

在我的程序世界中,我会做类似的事情:

In my procedural world, I'd do something like:

for (row in dataFrame) {
    #look up stuff using data from the row
    #write stuff to the file
}

执行此操作的R 方式"是什么?

What is the "R way" to do this?

推荐答案

你可以试试这个,使用 apply() 函数

You can try this, using apply() function

> d
  name plate value1 value2
1    A    P1      1    100
2    B    P2      2    200
3    C    P3      3    300

> f <- function(x, output) {
 wellName <- x[1]
 plateName <- x[2]
 wellID <- 1
 print(paste(wellID, x[3], x[4], sep=","))
 cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}

> apply(d, 1, f, output = 'outputfile')

这篇关于对于 R 数据框中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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