需要帮助在 R 中实现功能 [英] Need help implementing a function in R
问题描述
我正在尝试以一种利用脚本的方式进行编码,因为我经常以这种格式获得输出,并且不得不在 Excel 中一一复制/粘贴它是一项真正的苦差事.但是,我在实现功能方面遇到了困难.
I'm trying to code in such a way as to take advantage of scripting, as I regularly get output in this format and having to copy/paste it in Excel one by one is a real chore. However, I'm stuck when it comes to implementing the functions.
因此,我的数据采用以下形式:
So, my data is in the following form:
Condition Sample1 Sample2 .... Sample n
T1 6.99 5.80 .... n_1
T2 2.05 3.04 .... n_1
T3 4.50 4.69 .... n_1
T4 4.71 5.22 .... n_1
T5 5.66 3.65 .... n_1
T6 9.76 2.89 .... n_1
我需要应用以下等式:,其中 x 是单个条目,n 是系数,这样整个方程看起来像这样:
I need to apply the following equation: , where x is the individual entry and n is a coefficient, such that the full equation looks something like this:
.
基本上,每列,我需要按顺序考虑每个元素,并将其乘以序列系数(来自 1 的奇数:长度条件)以获得每个样本的答案 S.我的数据集的大小不会改变——它总是 T1:T6,改变的是样本 1...n.理想情况下,S 的值将附加在列的底部,或者保存在一个单独的数据集中,参考它所属的样本.
Basically, per column, I need to consider each element in sequence and multiply it by a sequential coefficient (odd numbers from 1: length Condition) to get the answer S, for each Sample. The size of my dataset will not change - it will always be T1:T6, what will change is Sample 1...n. Ideally the value of S will be appended at the bottom of the column, or saved in a separate dataset with reference to the sample that it belongs to.
我尝试了许多解决方案,包括移调,但似乎无法解决它.
I've tried a number of solutions, including transposing, but can't seem to wrap my head around it.
我目前尝试在数据集的一部分上实现更简单的函数没有成功.
My current attempt at implementing a simpler function on a portion of the dataset yielded no success.
for (i in 2:8){dT[7,i] <-
((1*dT[1,i])+(3*dT[2,i])+(5*dT[3,i])+(7*dT[4,i])+(9*dT[5,i]))+(11*dT[6,i])
}
我认为正确的解决方案涉及某种*apply,但我完全不知道如何正确使用它们.
I think the right solution involves some kind of *apply but I'm completely clueless as to how to use those properly.
添加可重现的示例:
N Condition Sample A Sample B Sample C Sample D
1 T1 91.323 78.758 70.298 66.765
3 T2 -3.737 -1.5 -7.744 -9.247
5 T3 5.205 4.533 2.284 2.178
7 T4 -0.486 -0.068 -1.386 -0.927
9 T5 0.337 -0.139 0.087 0.055
S -0.046296296 -0.123654391 0.394039047 0.445258425
推荐答案
看起来很简单.由于 R
是向量化的,所以使用向量的乘法.然后sum
.
Seems simple. Since R
is vectorized use vectors' multiplication. And then sum
.
zirconium <- function(x){
n <- 2*seq_along(x) - 1
sum(x * (-1)^((n - 1)/2))
}
sapply(dT[-1], zirconium)
#Sample1 Sample2
# 0.63 2.99
数据.
dT <-
structure(list(Condition = structure(1:6, .Label = c("T1", "T2",
"T3", "T4", "T5", "T6"), class = "factor"), Sample1 = c(6.99,
2.05, 4.5, 4.71, 5.66, 9.76), Sample2 = c(5.8, 3.04, 4.69, 5.22,
3.65, 2.89)), .Names = c("Condition", "Sample1", "Sample2"), class = "data.frame", row.names = c(NA,
-6L))
这篇关于需要帮助在 R 中实现功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!