首页 > 解决方案 > 如何将一段 R 代码应用于我的数据框的每一列

问题描述

我必须分析 EMG 数据,但我不太擅长使用 R:我有一个包含 9 列的 data.frame:一列指定时间,另外 8 列指定我的频道。我想过滤我的 emg 数据,但我只能按通道执行此操作,但我想一次对数据帧的所有通道执行此操作,因此我不必将其应用于每个通道。

# This example computes the LE-envelope using the lowpass routine

# Coerce a data.frame into an 'emg' object
x <- as.emg(extensor_raw$channel1, samplingrate = 1000, units = "mV")  ##do this for every channel

# Compute the rectified signal
x_rect <- rectification(x)

# Filter the rectified signal
y <- lowpass(x_rect, cutoff = 100)

# change graphical parameters to show multiple plots
op <- par(mfrow = c(3, 1))

# plot the original channel, the filtered channel and the 
# LE-envelope
plot(x, channel = 1, main = "Original  channel")
plot(x_rect, main = "Rectified  channel")
plot(y, main = "LE-envelope")

# reset graphical parameters
par(op)

所以我可以在这里使用 extensor_raw$channel1 代替 extensor_raw$i 并围绕它循环吗?或者有没有办法将这段代码应用于每个通道(即 9 列数据帧的 8 列,不包括指定时间的第一列?)

标签: rloopsfilterapply

解决方案


如果它是按列的,则使用lapply并存储为 alist并假设所有列都需要更改。(请注意,这未经测试。可能必须更改parin )plot

lst1 <- lapply(extensor_raw, \(vec) {
      x <- as.emg(vec, samplingrate = 1000, units = "mV")  

      # Compute the rectified signal
       x_rect <- rectification(x)
     # Filter the rectified signal
     y <- lowpass(x_rect, cutoff = 100)

     # change graphical parameters to show multiple plots
     op <- par(mfrow = c(3, 1))

     # plot the original channel, the filtered channel and the 
    # LE-envelope
     plot(x, channel = 1, main = "Original  channel")
    plot(x_rect, main = "Rectified  channel")
     plot(y, main = "LE-envelope")


# reset graphical parameters
par(op)
})

推荐阅读