[R] How to create a loop and then extract values from the list generated by cor.test
Keith Larson
keith.larson at biol.lu.se
Tue Dec 27 22:05:48 CET 2011
Dear all,
I would like to conduct a Pearson's correlation using cor.test
separately for each individual in my data set. Each individual has
nine observations of the measurement variable 'Delta13C'. I can figure
our how to do it manually one 'Individual_ID' at a time, but I cannot
figure out how to automate the process (a loop I am guessing). In
addition, I would like to generate a new data frame that has the each
individual's 'Individual_ID', the pearson correlation 'estimate', and
the 'p.valve'.
The output table would look something like:
Individual_ID, estimate, p.value
WW_08A_02, -0.7670675, 0.01586
WW_08A_03, -0.02320767, 0.9527
Code with sample data:
## Create sample dataset
WW_Wing_SI <-
structure(list(Individual_ID = c("WW_08A_02", "WW_08A_02", "WW_08A_02",
"WW_08A_02", "WW_08A_02", "WW_08A_02", "WW_08A_02", "WW_08A_02",
"WW_08A_02", "WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03",
"WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03"
), FeatherPosition = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4,
5, 6, 7, 8, 9), Delta13C = c(-18.67, -19.16, -20.38, -20.96,
-21.61, -21.65, -21.31, -20.8, -21.28, -20.06, -20.3, -21.21,
-22.9, -22.87, -21.13, -20.68, -20.58, -20.69)), .Names = c("Individual_ID",
"FeatherPosition", "Delta13C"), row.names = c(NA, 18L), class = "data.frame")
## Create vector with unique individual IDs
WW_Wing_Individuals <- unique(WW_Wing_SI$Individual_ID)
## Create temp dataset with for the first individual
temp <- WW_Wing_SI_Spring[ which(WW_Wing_SI_Spring$Individual_ID ==
WW_Wing_Individuals[1]), ]
## Create temp2 dateset with results of pearsons product-moment
correlation (for the first individual)
temp2 <- cor.test(temp$Delta13C, temp$FeatherPosition, method="pearson")
Many Cheers,
Keith
*******************************************************************************************
Keith Larson, PhD Student
Evolutionary Ecology, Lund University
Sölvegatan 37
223 62 Lund Sweden
Phone: +46 (0)46 2229014 Mobile: +46 (0)73 0465016 Fax: +46 (0)46 2224716
Skype: sternacaspia FB: keith.w.larson at gmail.com
More information about the R-help
mailing list