簡體   English   中英

如何創建一個新列,其值取決於其他列中的值?

[英]How do I create a new column with values that depend on the values in other columns?

這是一個非常簡單的玩具數據集,用於說明我目前在使用另一個數據集時遇到的問題。

假設我們在數學測試中測試了 4 名參與者,他們每個人都回答了 4 個問題。 這些問題中有 2 個問題很容易,其中 2 個問題很困難。 但是問題是隨機出現的,所以有些人從簡單的問題開始,有些人從困難的問題開始。 在這個實驗中我們有一個二元響應變量,我們將答案分類為“正確”或“不正確”。

以下是假數據:

my_matrix <- matrix(c(rep(1:4, each=4), rep(1:4, 4), rep(c("difficult", "easy"), times = 4), rep(c("easy", "difficult"), times = 4), rep(c("correct", "incorrect"), times = 8)), nrow=16, ncol=4, byrow = FALSE)

my_matrix

my_data_frame <- as.data.frame(my_matrix)

colnames(my_data_frame) <- c("Participant", "ItemNumber", "QuestionDifficulty", "Answer")

my_data_frame$Participant <- as.numeric(my_data_frame$Participant)

my_data_frame

現在,我想創建一個新列,這樣它的值對於從困難問題開始的人來說是“困難第一”,對於從簡單問題開始的人來說是“EasyFirst”。 我為此嘗試了以下代碼。

for (i in 1:16) {
  ifelse(my_data_frame$Participant == i & my_data_frame$ItemNumber == 1 & my_data_frame$QuestionDifficulty =="difficult",
         my_data_frame$FirstQuestion[((i*4)-3):(i*4)] <- "DifficultFirst",
         my_data_frame$FirstQuestion[((i*4)-3):(i*4)] <- "EasyFirst")}

但它沒有用。 具體來說,我收到了一條關於替換和行號不匹配的數據的錯誤消息,我不知道為什么會這樣。

天已經晚了,我的大腦可能太累了,如果這是一個愚蠢的問題,請見諒。 但任何幫助將不勝感激。 謝謝!

不需要循環,可以使用各種分組操作。 ItemNumber ParticipantItemNumber排列數據,按Participant將其分組並獲得QuestionDifficulty的第一個值。

library(dplyr)

my_data_frame %>%
  arrange(Participant, ItemNumber) %>%
  group_by(Participant) %>%
  mutate(FirstQuestion = paste0(first(QuestionDifficulty), "first"))

#   Participant ItemNumber QuestionDifficulty Answer    FirstQuestion 
#         <dbl> <fct>      <fct>              <fct>     <chr>         
# 1           1 1          difficult          correct   difficultfirst
# 2           1 2          easy               incorrect difficultfirst
# 3           1 3          difficult          correct   difficultfirst
# 4           1 4          easy               incorrect difficultfirst
# 5           2 1          difficult          correct   difficultfirst
# 6           2 2          easy               incorrect difficultfirst
# 7           2 3          difficult          correct   difficultfirst
# 8           2 4          easy               incorrect difficultfirst
# 9           3 1          easy               correct   easyfirst     
#10           3 2          difficult          incorrect easyfirst     
#11           3 3          easy               correct   easyfirst     
#12           3 4          difficult          incorrect easyfirst     
#13           4 1          easy               correct   easyfirst     
#14           4 2          difficult          incorrect easyfirst     
#15           4 3          easy               correct   easyfirst     
#16           4 4          difficult          incorrect easyfirst

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM