Updating existent matrix with a new column that stores different p-values in rows

Liviosah :

I have this code I have written:

my.data = matrix(rnorm(20000), ncol = 20)
View(my.data)

empty5 = character()
empty10 = character()

for (variable in 1:nrow(my.data)) {

  nrFirst5 = my.data[variable,c(1,2,3,4,5)]
  nrSecond5 = my.data[variable,c(6,7,8,9,10)]

  nrFirst10 = my.data[variable,c(1,2,3,4,5,6,7,8,9,10)]
  nrSecond10 = my.data[variable,c(11,12,13,14,15,16,17,18,19,20)]
  #print(nrSecord)

  ttColumn5 = t.test(nrFirst5, nrSecond5, data = my.data, paired = TRUE)
  pp5 = ttColumn5$p.value
  #print(pp5)

  ttColumn10 = t.test(nrFirst10, nrSecond10, data = my.data, paired = TRUE)
  pp10 = ttColumn10$p.value
  #print(tt)

  #my.data$p5 = my.data[pColumn5]
  #my.data$p10 = my.data[pColumn10]

  pplace5 = append(empty5,pp5)

  pplace10 = append(empty10,pp10)

}


my.data <- cbind(my.data, pplace5)

View(my.data)

It gets all of the p-values that I want. However, I cannot seem to figure out how to update the my.data matrix with another column that has those p-values. Right now it creates a new column called place5 but it stores the same exact number in all of the rows. But I want it to store different p-values in those rows. Could someone help?

I have also tried like so

my.data$place5 = my.data$pplace5

But it gives me an error. Like this:

$ operator is invalid for atomic vectors

DzimitryM :

Option 1

my.data = matrix(rnorm(20000), ncol = 20)
pplace5 = character()
pplace10 = character()

for (variable in 1:nrow(my.data)) {
  pp5 = t.test(my.data[variable,c(1:5)], my.data[variable,c(6:10)], paired = TRUE)$p.value
  pp10 = t.test(my.data[variable,c(1:10)], my.data[variable,c(11:20)], paired = TRUE)$p.value

  pplace5 = append(pplace5, pp5)
  pplace10 = append(pplace10, pp10)
}
my.data <- cbind(my.data, pplace5)
my.data <- cbind(my.data, pplace10)

Option 2 (shorter and faster):

my.data = matrix(rnorm(20000), ncol = 20)

aa <- apply(my.data, 1, function(x) {
  pp5 = t.test(x[1:5], x[6:10], paired = TRUE)$p.value
  pp10 = t.test(x[1:10], x[11:20], paired = TRUE)$p.value
  c(pp5, pp10)
})

my.data <- cbind(my.data, t(aa))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390421&siteId=1