簡體   English   中英

比較數據框中的 2 列並在數據框中創建新列

[英]comparing 2 columns in a data-frame and creating a new column in data frame

我從 2 個數據框中“合並”了數據,並且比較了 2 列“answer”和“selected_answer”,通過執行以下代碼,我在 final_ans 列中得到了 true 和 false 值,

dt$final_ans<- dt$correct_answer==dt$selected_answer

但我想根據列final_ans的值添加另一列“分數”,如果為真,則希望在列分數中顯示 3,如果為假則顯示 0。下面是我所做的代碼,但答案錯誤。 它只為所有行顯示 0,如下所示.. 如何編輯代碼以獲取精確值。

    Q_id c1  c2 c3 c4 answer stu_id selected_answer  final_ans score
     2   1   2  3   4   2    82       3                false     0
     3   1   2  3   4   2    58       3                false     0
     3   1   2  3   4   2    83       2                true      0
     3   1   2  3   4   2    100      3
     4   1   2  3   4   1    79       3
     5   1   2  3   4   1    100      3
     7   1   2  3   4   1    54       3
     7   1   2  3   4   1    92       3
     8   1   2  3   4   3    56       2

你可以這樣做:

dt <- data.frame(a=1:5, b=5:1) # here are your 2 'answer' columns
dt$test <- dt$a==dt$b # here is your test for correct answer
dt$score <- dt$test * 3 # here is the score you give for a 'TRUE' answer
dt

將邏輯向量乘以 3,您將TRUE替換為 3,將FALSE替換為 0。即,

rt$is_correct <- dt$correct_answer==dt$selected_answer
rt$is_correct * 3 

如果您的帶有final_ans的列不是邏輯的,而是一個字符,那么您需要先轉換它,然后創建您的新列。

dt$final_ans <- as.logical(dt$final_ans) #to convert to logical
dt$score <- dt$final_ans * 3 #to create your new column

暫無
暫無

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

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