问题
I have a dataset called "My_data", and three variables called a, b, c. The head of my data is like this:
> head(My_data)
variable_A variable_B value
1 Jul W1 18.780294
2 Jul W2 13.932397
3 Aug W2 20.877093
4 Sep W3 9.291295
5 May W1 10.939570
6 Oct W1 12.23671
I want to do Shapiro normality test for each subset with two variables.
> Subset1=subset(My_data, variable_A== "Jan" & variable == "W1")
> Subset2=subset(My_data, variable_A== "Feb" & variable == "W1")
> Subset3=subset(My_data, variable_A== "Mar" & variable == "W1")
.
.
> Subset_n=subset(My_data, variable_A== "Jan" & variable == "W2")
>
Subset_n2=subset(My_data, variable_A== "Jan" & variable == "W3")
You see that I need to make a lot of subsets and do Shapiro for each one.
But if I can loop it, it makes my job easier.
I have this code for lopping
> loop_Shapiro = list()
> for (ids in unique(My_data$variable_A)){
+ My_sub = subset(x=My_data, subset=variable_A==ids)
+
+ loop_Shapiro[[ids]] = shapiro.test(My_sub$value)
+ }
This loop works, but the problem is that it is only based subletting with one variable, but I want for two.
回答1:
First, let's create an example data frame.
# Create example data frame
set.seed(18800)
My_data <- data.frame(
variable_A = rep(month.abb, each = 30),
variable_B = rep(paste0("W", 1:3), times = 120),
value = rnorm(360)
)
We can split the data frame using split without the use of subset. The result is a list.
# Split the data frame
My_list <- split(My_data, f = list(My_data$variable_A, My_data$variable_B))
After that, we can use for-loop as follows.
loop_Shapiro <- list()
for (name in names(My_list)){
My_sub <- My_list[[name]]
loop_Shapiro[[name]] <- shapiro.test(My_sub$value)
}
# Check the results of the first shapiro test
loop_Shapiro[1]
# $Apr.W1
#
# Shapiro-Wilk normality test
#
# data: My_sub$value
# W = 0.89219, p-value = 0.1794
We can also consider using the lapply function after the split. The result is a list.
# Use lapply
loop_Shapiro2 <- lapply(My_list, function(x) shapiro.test(x$value))
loop_Shapiro2[1]
# $Apr.W1
#
# Shapiro-Wilk normality test
#
# data: x$value
# W = 0.89219, p-value = 0.1794
来源:https://stackoverflow.com/questions/58253937/loop-for-shapiro-wilk-normality-test-for-multiple-variables-in-r