简体   繁体   中英

Extracting several p-values to dataframe column

I have two columns, x=successes, y=total sample. I want to run binom.test on each of the 30 rows in the df, extract the p-value and store it in a column. So far this is frustrating all my efforts, and I can't see why. Example code

Pvalues <- data.frame(matrix(ncol=1,nrow=30)) # Creates the dataframe "Pvalues"
names(Pvalues) <- paste0("Pvalues",1:1) # Names the column
head(Pvalues)
Pvalues[Pvalues1] <- with(NewData,binom.test(NumberMeetingTargetAggregate,NumberOfAttendancesAggregate,0.95)$p.value)

error message
Error in binom.test(NumberMeetingTargetAggregate, NumberOfAttendancesAggregate,  : 
  incorrect length of 'x'

you can use apply statement to apply the function on each row.

# sample data
df <- data.frame(x = 10:15, y = 20:25)

# apply function to each row
df[['p.value']] <- apply(df, 1, function(row) binom.test(row[1],row[2])$p.value)
df
# x  y   p.value
# 1 10 20 1.0000000
# 2 11 21 1.0000000
# 3 12 22 0.8318119
# 4 13 23 0.6776395
# 5 14 24 0.5412562
# 6 15 25 0.4243562

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM