R中列中的随机值
Random value in column in R
有没有人知道如何生成随机值列,其中只有一个随机行标有数字“1”。所有其他的都应该是“0”。
我需要 R 代码中的函数。
这是我需要的照片:
> x <- rep(0, 10)
> x[sample(1:10, 1)] <- 1
> x
[1] 0 0 0 0 0 0 0 1 0 0
df <- data.frame(subject = 1, choice = 0, price75 = c(0,0,0,1,1,1,0,1))
此命令将在每次调用时更新 choice
列以包含值为 1
的单个随机行。 choice
列中的所有其他行值都设置为 0
.
df$choice <- +(seq_along(df$choice) == sample(nrow(df), 1))
使用 integer(length(DF$choice))
创建一个 0
的矢量,其中 [<-
替换 sample(length(DF$choice), 1)
.
位置上的 1
DF <- data.frame(subject=1, choice="", price75=c(0,0,0,1,1,1,0,1))
DF$choice <- `[<-`(integer(nrow(DF)), sample(nrow(DF), 1L), 1L)
DF
# subject choice price75
#1 1 0 0
#2 1 0 0
#3 1 0 0
#4 1 1 1
#5 1 0 1
#6 1 0 1
#7 1 0 0
#8 1 0 1
在 R
中的 row\column 中设置随机值的多种方法
df<-data.frame(x=rep(0,10)) #make dataframe df, with column x, filled with 10 zeros.
set.seed(2022) #set a random seed - this is for repeatability
#two base methods for sampling:
#sample.int(n=10, size=1) # sample an integer from 1 to 10, sample size of 1
#sample(x=1:10, size=1) # sample from 1 to 10, sample size of 1
df$x[sample.int(n=10, size=1)] <- 1 # randomly selecting one of the ten rows, and replacing the value with 1
df
有没有人知道如何生成随机值列,其中只有一个随机行标有数字“1”。所有其他的都应该是“0”。
我需要 R 代码中的函数。
这是我需要的照片:
> x <- rep(0, 10)
> x[sample(1:10, 1)] <- 1
> x
[1] 0 0 0 0 0 0 0 1 0 0
df <- data.frame(subject = 1, choice = 0, price75 = c(0,0,0,1,1,1,0,1))
此命令将在每次调用时更新 choice
列以包含值为 1
的单个随机行。 choice
列中的所有其他行值都设置为 0
.
df$choice <- +(seq_along(df$choice) == sample(nrow(df), 1))
使用 integer(length(DF$choice))
创建一个 0
的矢量,其中 [<-
替换 sample(length(DF$choice), 1)
.
1
DF <- data.frame(subject=1, choice="", price75=c(0,0,0,1,1,1,0,1))
DF$choice <- `[<-`(integer(nrow(DF)), sample(nrow(DF), 1L), 1L)
DF
# subject choice price75
#1 1 0 0
#2 1 0 0
#3 1 0 0
#4 1 1 1
#5 1 0 1
#6 1 0 1
#7 1 0 0
#8 1 0 1
在 R
中的 row\column 中设置随机值的多种方法df<-data.frame(x=rep(0,10)) #make dataframe df, with column x, filled with 10 zeros.
set.seed(2022) #set a random seed - this is for repeatability
#two base methods for sampling:
#sample.int(n=10, size=1) # sample an integer from 1 to 10, sample size of 1
#sample(x=1:10, size=1) # sample from 1 to 10, sample size of 1
df$x[sample.int(n=10, size=1)] <- 1 # randomly selecting one of the ten rows, and replacing the value with 1
df