2
votes

The below dataset and code creates a new dataset with the results from cor.test being performed on each individual ('Individual_ID') from my original dataset. How do I convert each variable from the cor.test results to a numeric data type, as it is passed into the new dataframe? For example, 'estimate', 'p.value', and 'conf.int' should be numeric not character. Second, I would like variable 'conf.int' to be two variables, 'lowlim' and 'uplim'.

## 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")

# split data frame according the the individual IDs
individual.list <- split(WW_Wing_SI, WW_Wing_SI$Individual_ID)

# apply cor.test() with extract to each element of the list
test <- as.data.frame(t(sapply(individual.list, function(temp)
                        cor.test(temp$Delta13C, temp$FeatherPosition,
                        method="pearson")[c("estimate", "p.value", "conf.int")])))
1

1 Answers

4
votes

This is how I'd do it. If you do everything "right", the output is already in numeric so no coercion is necessary (if not, you would use as.numeric(object$variable)). When I create the inter variable, I insert the desired components so that I can construct lower/upper CI variables. Notice, that test is now a "proper" data.frame that can be easier to work with (you can easily extract any item you want).

# split data frame according the the individual IDs
individual.list <- split(WW_Wing_SI, WW_Wing_SI$Individual_ID)

# apply cor.test() with extract to each element of the list
inter <- sapply(individual.list, function(temp) {
            a <- cor.test(temp$Delta13C, temp$FeatherPosition,
                    method="pearson")[c("estimate", "p.value", "conf.int")]
            out <- data.frame(cor = a$estimate, p.value = a$p.value, lowerCI = a$conf.int[1], upperCI = a$conf.int[2])
        }, simplify = FALSE)
test <- do.call("rbind", inter)
test

                  cor    p.value    lowerCI    upperCI
WW_08A_02 -0.76706752 0.01585509 -0.9481677 -0.2098478
WW_08A_03 -0.02320767 0.95274294 -0.6768966  0.6509469