需要帮助在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:长度条件开始的奇数),以获得每个Sample的答案 S .我的数据集的大小不会改变-它将始终为T1:T6,将改变的是Sample 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屋!