将函数应用于数据帧变量的子部分并将其保存到原始数据帧的 R 代码
我有一个像 mtcars 这样的数据框,
我想编写一个函数来搜索以“c”开头的 mtcars 的所有变量,将它们转换为字符并将它们保存回 mtcars。
I have a dataframe like mtcars
I want to program a function that searches for all variables of mtcars that start with "c", converts them to character and saves them back to mtcars.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法:
[编辑:实现 @hadley 在评论中提出的观点的替代版本。]
该函数允许您传递要匹配的字符串,但默认为
"^var"
按照您的要求。"^"
表示我们要查找以"var"
开头的名称,而不是任何包含"var"
的名称。例子:
Here is one way:
[Edit: alternative version that implements the points raised by @hadley in comments.]
The function allows you to pass through the string you want to match on, but defaults to
"^var"
as you requested. The"^"
indicates we want to find names that start with"var"
, not any name that contains"var"
.Example:
另一种变体说明了 grep 的另一个功能和另一个版本的“[”运算符:
value=TRUE 参数返回匹配的名称而不是它们的位置。您实际上并不需要使用
[ , Want]
,只需使用[want]
因为这是一个完整的按列操作。检查它(和辛普森的版本)是否返回完整的 data.frame,即使没有列匹配。请不要“接受”这个答案......它只不过是一条评论,但很难阅读评论中的函数结构。Another variation that illustrates another features of grep and another version the "[" operator:
The value=TRUE argument returns the matching names rather than their position. You don't really need to use
[ , want]
and can instead just use[want]
since this is a full column-wise operation. Checked to see that it (and Simpson's versions) returns the full data.frame even if no columns match. Please don't "accept" this answer ... it's not much more than a comment, but it's really hard to read function structure in the comments.