[英]Create new column based on another column from dataframe with rnorm function
I'm trying use column values in rnorm function and creating new column bound data frame.我正在尝试使用 rnorm function 中的列值并创建新的列绑定数据框。
> show(tablo)
teta
1 14.67078
2 14.86293
3 15.54010
4 15.91335
5 16.05241
6 15.24349
7 15.01060
8 14.79570
each teta values mean values in rnorm function.每个 teta 值均以 rnorm function 表示。 First I created function首先我创建了 function
values <- function(x)
{
rnorm(1, x, 0.55)
}
values(tablo$teta) or attach(tablo) values(teta)
This function shows just one value.这个 function 只显示一个值。
which is odd.这很奇怪。
a <- 1:10
test <- function(x) {
x +20
}
test(a)
This function shows all new a values for a.此 function 显示了 a 的所有新 a 值。
You should use length(x)
rather than 1
within rnorm
, eg,您应该在rnorm
中使用length(x)
而不是1
,例如,
rnorm(length(x),x,0.55)
Use apply family of functions (eg sapply
) function, as you want to utilize your function values
on each element of a vector.使用apply系列函数(例如sapply
)function,因为您想在向量的每个元素上使用 function values
。 Following should do the job:以下应该做的工作:
sapply(tablo$teta,values)
#[1] 14.88455 14.07981 15.19649 16.12940 16.42719 14.69165 14.27466 13.57540
Your test
function worked without using sapply
because +
operation in R is a vector operation.您的test
function 在不使用sapply
的情况下工作,因为 R 中的+
操作是矢量操作。 However, It did not work with values
function because in rnorm , mean (ie 2nd argument) should be passed as a scalar if n (first argument) is 1 (while in your question are passing it in as a vector).但是,它不适用于values
function 因为在rnorm中,如果 n (第一个参数)为 1 (而在您的问题中将其作为向量传递),则平均值(即第二个参数)应该作为标量传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.