R:使用现有值创建新列,以另一列的组为条件
我正在研究一个眼动追踪数据集,希望将现有列中的值分配给新列,以第二个现有列为条件。
我有列:带有因子 left 和 right 的“targetlocation”、带有数值的“right_looks”和带有数值的“left_looks”。
我想要做的是:
- 为“target_looks”和“distractor_looks”创建新列,其中:
- 如果“targetlocation”为right,则“right_looks”中的值将分配给“target_looks”,并且“ left_looks”被分配给“distractor_looks”
- 如果“targetlocation”是left,那么“left_looks”中的值将被分配给“target_looks”,并且来自“target_looks”的值将被分配给“target_looks” “right_looks”被分配给“distractor_looks”
我尝试创建第一个空列,然后填充它们,但也许 mutate() 或 if_else() 语句在这里效果更好。有什么解决办法吗?
I am working on an eye-tracking dataset want to assign values from existing columns to new columns, conditional on a second existing column.
I have columns: "targetlocation" with factors left and right, "right_looks" with numerical values, and "left_looks" with numerical values.
What I want to do is:
- Create new columns for "target_looks" and "distractor_looks" where:
- If “targetlocation” is right, then values from “right_looks” are assigned to “target_looks” and values from “left_looks” are assigned to “distractor_looks”
- If “targetlocation” is left, then values from “left_looks” are assigned to “target_looks” and values from “right_looks” are assigned to “distractor_looks”
I have tried creating first empty columns and then populating them, but maybe a mutate() or if_else() statement works better here. Are there any solutions for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是示例数据的另一种方法。为了清楚起见,我创建了一个带有“左”和“右”的简单2个元素向量。您的
TargetLocation
可以是这些级别的因素,而nontargetLocation
将是该因素的反向级别。您可以使用GET
根据“左”或“右”提取适当的列名的值。输出
Here is another approach with example data. For clarity, I created a simple 2 element vector with "left" and "right". Your
targetlocation
can be a factor with those levels, and anontargetlocation
would be the reversed levels of that factor. You can useget
to extract the value for the appropriate column name based on "left" or "right".Output
这是一种选择。
Here is one option.